// 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