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 map = new HashMap();
map.put("A", "1");
map.put("B", "2");
map.put("C", "2");
map.put("D", "3");
map.put("E", "3");
Set keys = map.keySet(); // The set of keys in the map.
Iterator 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);
}
解决方案
make a reverse HashMap!
HashMap map = new HashMap();
Set keys = map.keySet(); // The set of keys in the map.
Iterator keyIter = keys.iterator();
while (keyIter.hasNext()) {
String key = keyIter.next();
String value = map.get(key);
map.add(value, key);
}
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