开发者

How to avoid inserting duplicate values in a HashMap?

开发者 https://www.devze.com 2023-04-02 05:58 出处:网络
Let say we have : Map hm = new HashMap(); 开发者_如何学C How to avoid putting duplicate values(Emplyees) in this HashMap?I assume you are coding in Java, so:

Let say we have : Map hm = new HashMap();

开发者_如何学C

How to avoid putting duplicate values(Emplyees) in this HashMap?


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.


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;
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号