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
CodePudding user response:
map.remove(arr[i]);
removes the entry, and your code does not put any new entry back in its place.
The simplest fix is just to replace
if(map.containsKey(arr[i])){
map.remove(arr[i]);
} else {
map.put(arr[i],i);
}
with
map.put(arr[i],i);
CodePudding user response:
As an addendum to Louis' answer, you don't need the a map here, because you don't use the value.
Just use a HashSet
:
HashSet<Integer> set = new HashSet<>();
for(int i=0; i<arr.length; i ){
set.add(arr[i]);
}
// Or:
// HashSet<Integer> set = Arrays.stream(arr).boxed().collect(Collectors.toCollection(HashSet::new));
set.forEach(k-> System.out.print(k " "));
Actually, the way HashSet
is implemented is just using a HashMap
: the values you add to the Set
are the map keys; the value stored for each key is some arbitrary value. See this question for more details.
Note that with either a HashSet
or HashMap
you don't get a reliable iteration order. If you want the entries to appear in the encounter order, use a LinkedHashSet
(/LinkedHashMap
).