why this code is not giving me the desired output?As we use hashmaps to implement key value pairs
and the keys are unique. So this can remove the duplicate elements from the array. But instead of removing duplicate elements it is removing some of the actual elements.
package hashmaps;
import java.util.HashMap;
public class HashMap01 {
public static void main(String[] args) {
int[] arr = {1,2,2,4,5,5,5,7,66,65,65};
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0; i<arr.length; i++){
if(map.containsKey(arr[i])){
map.remove(arr[i]);
} else {
map.put(arr[i],i);
}
}
map.forEach((k,v)-> System.out.print(k+" "));
}
}
I want
1,2,4,5,7,66,65
But getting 1,66,4,5,7