Wednesday, February 2, 2022

Remove duplicate element from array

                // remove duplicate from an array using set

int[] ar = { 1, 1, 2, 3, 4, 5, 6, 6, 7, 8 };

Set<Integer> uniqueElements = new HashSet<>();

for (int i = 0; i < ar.length; i++) {

uniqueElements.add(ar[i]);

}

for (Integer i : uniqueElements) {

System.out.print(i+" ");

}

                  //Using HashMap

Map<Integer, Integer> uniqueElements = new HashMap<>();

for (int i = 0; i < ar.length; i++) {

if (uniqueElements.get(ar[i]) == null) {

System.out.print(ar[i] + " ");

uniqueElements.put(ar[i], ar[i]);

}

}


No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...