I have a map with duplicate values:
("A", "1");
("B", "2");
("C", "2");
("D", "3");
("E", "3");
I would like to the map to have
("A", "1");
("B", "2");
("D", "3");
Do you know how to get rid of the duplicate values?
At present, I get 'java.util.ConcurrentModificationException' error.
Thank you.
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("A", "1");
map.put("B", "2");
map.put("C", "2");
map.put("D", "3");
map.put("E", "3");
Set<String> keys = map.keySet(); // The set of keys in the map.
Iterator<String> keyIter = keys.iterator();
while (keyIter.hasNext()) {
String key = keyIter.next();
String value = map.get(key);
System.out.println(key + "\t" + value);
String nextValue = map.get(key);
if (value.equals(nextValue)) {
map.remove(key);
}
}
System.out.println(map);
}
This will be helpful to remove duplicate values from map.
System.out.println("mymap :" + mymap);
Output:
mymap :{1=One, 2=Two, 4=Three}
This can be easily done by putting your hashmap into arraylist. This arraylist is of hashmap type.
Now print your arraylist...all the duplicate values from the hashmap easily removed...This is the easiest way to remove duplicacy
make a reverse HashMap!
now that you have the hashMap you need reverse it or print it.
in anyway do not delete while iterating hashMap. save the values in a list and delete them in an outer loop
If you are looking just to remove the concurrentModification exception, then just replace your HashMap with ConcurrentHashMap.
To know more about ConcurrentHashMap look here
Assuming that you use Java 8, it could be done using the
Stream API
with aSet<String>
that will store the existing values:Output:
NB: Strictly speaking a predicate of a filter is not supposed to be stateful, it should be stateless as mentioned into the javadoc in order to ensure that the result remain deterministic and correct even if we use a parallel stream. However here, I assume that you don't intend to use a parallel stream such that this approach remains valid.