Reputation: 21
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?
Upvotes: 0
Views: 2263
Reputation: 9018
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.
Upvotes: 1
Reputation: 53859
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
Upvotes: 2
Reputation: 6099
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.
Upvotes: 3
Reputation: 312219
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.
Upvotes: 2