What is wrong with my code? I'm trying to print the keys but when I print the I'm getting duplicate keys. I was under the impression that when we add duplicate keys to hashmap, it replaces the previous key.
I'm trying to print all the repeating elements in the array.
public static void repeatingElements(int a[], int n) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
if (map.containsKey(a[i])) {
map.put(a[i], map.get(a[i]) + 1);
} else {
map.put(a[i],1);
}
for (Map.Entry<Integer, Integer> entry: map.entrySet()) {
if (entry.getValue()>1) {
System.out.print(entry.getKey() + " ");
}
}
}
}
{12, 10, 9, 45, 2, 10, 10, 45}
10 45
10 10 10 45
The output you are getting is a result of emiting the status of the Map on each iteration of the for loop.
Consider the state of the Map on each iteration:
12: [{12:1}] Output:
10: [{12:1}, {10:1}] Output:
9: [{12:1}, {10:1}, {9:1}] Output:
45: [{12:1}, {10:1}, {9:1}, {45:1}] Output:
2: [{12:1}, {10:1}, {9:1}, {45:1}, {2:1}] Output:
10: [{12:1}, {10:2}, {9:1}, {45:1}, {2:1}] Output: 10
10: [{12:1}, {10:3}, {9:1}, {45:1}, {2:1}] Output: 10
45: [{12:1}, {10:3}, {9:1}, {45:2}, {2:1}] Output: 10 45
So the total output ends up as: 10 10 10 45
Solution is to move that status output after the loop.
public static void repeatingElements(int a[], int n){
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0;i<n;i++){
if(map.containsKey(a[i])){
map.put(a[i], map.get(a[i]) + 1);
} else {
map.put(a[i],1);
}
}
for(Map.Entry<Integer, Integer> entry: map.entrySet()){
if(entry.getValue()>1){
System.out.print(entry.getKey() + " ");
}
}
}