Reputation: 517
Let say we have : Map hm = new HashMap();
How to avoid putting duplicate values(Emplyees) in this HashMap?
Upvotes: 1
Views: 10437
Reputation:
I think duplicate values in Map can be removed using this generic method if your userdefined object is overridden with equals and hashcode from object class
public static <K, V > Map<K,V> genericMethodtoDeleteMapduplicate(Map<K, V> pMap) {
Map<K,V> mapWithoutDup=new HashMap<>();
Set<V> totalvaluesPresent=new HashSet<>();
for (Map.Entry<K, V> a : pMap.entrySet()) {
if(totalvaluesPresent.add(a.getValue())){
mapWithoutDup.put(a.getKey(), a.getValue());
}
}
return mapWithoutDup;
}
Upvotes: 1
Reputation: 53869
I assume you are coding in Java, so:
if(!myMap.containsKey(myKey)){
myMap.put(myKey, myValue);
}
The good thing with HashMap
is that the containsKey
method takes constant time (or constant amortized time) regardless of the number of elements in your map so you can call it without bothering of the time it may take!
If you use an other language, the logic remains the same.
Upvotes: 2
Reputation: 592
Not sure what language you are using but in java for Hashmap their are:
boolean containsKey(Object key) - Returns true if this map contains a mapping for the specified key.
and
boolean containsValue(Object value) - Returns true if this map maps one or more keys to the specified value.
Just call which ever one makes more sense for you to check if the entry is already in the map, if it is then you know its a duplicate, otherwise put it in. I'm certain whatever language you are using will have something similar!!
Upvotes: 0