Remove duplicate values from HashMap in Java
duplicates, hashmap, java
Solution
make a reverse HashMap!
HashMap<String, String> map = new HashMap<String, String>();
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);
map.put(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
Problem
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); } ```