I have a HashMap in Java:
HashMap meh = new HashMap();`
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?
解决方案
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.