Java - how to remove duplicating entries from HashMap?

☆樱花仙子☆ 提交于 2019-12-11 14:13:23

问题


I have a HashMap in Java:

HashMap<String, Integer> meh = new HashMap<String, Integer>();`

meh.put("one", 1);
meh.put("one", 1);
meh.put("one", 1);
meh.put("two", 1);
meh.put("two", 2);
meh.put("three", 3);

What I need is to remove duplicating entries ("one", 1) [when both key and value duplicate]. I searched and found only 'how to remove duplicating keys/values'. Can anyone help?


回答1:


There is no need to do that, HashMap takes care of that automatically. What happens when you execute that code is essentially as follows:

meh.put("one", 1);

this makes the map {"one" -> 1}

meh.put("one", 1);

this replaces the assignment by itself, making the map {"one" -> 1}

meh.put("one", 1);

this replaces the assignment by itself, making the map {"one" -> 1}

meh.put("two", 1);

this adds the requested linking, making the map {"one" -> 1, "two" -> 1}

meh.put("two", 2);

this replaces the assignment for "two", making the map {"one" -> 1, "two" -> 2}

meh.put("three", 3);

this adds the new element, making the total mapping {"one" -> 1, "two" -> 2, "three" -> 3} with no duplicates involved.




回答2:


You cannot remove duplicates from a HashMap because there are no duplicates in a HashMap in the first place. The second (or third, or whatever) time you call put with a key that already exists in the map, it will simply override the value with a new one, regardless of whether it's a duplicate or not of the pre-existing one.

In the code snippet you provided, the map will only have three values.




回答3:


From what you describe, Map<String, Integer> is not the structure adapted to your needs: you do not seem to assiciate the value 2 to "two" but you are actually storing pairs of elements.

A better data structure might be to use a Set of MyPair where MyPair is:

public class MyPair {
    private String first;
    private int second;
    // + constructor, getters + setters, hashcode + equals
}

And then you can use that MyPair object in a HashSet:

Set<MyPair> myPairs = new HashSet();
myPairs.add(new MyPair("one", 1));
myPairs.add(new MyPair("one", 2));
myPairs.add(new MyPair("two", 2));    
myPairs.add(new MyPair("two", 2));
myPairs.remove(new MyPair("one", 2)); // remove MyPair("one", 2) only



回答4:


Your real question isn't how to remove duplicates.

It's how to preserve the unique values with duplicate keys.

See this answer https://stackoverflow.com/a/8229534/152578 by Jon Skeet for details, but basically you're looking for a multimap.

You'll have to check for the value on insertion.

Another choice would be to unite the key and value (method depending on your symbol space), and store them in a set.



来源:https://stackoverflow.com/questions/26243740/java-how-to-remove-duplicating-entries-from-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!