The simple solution is to fix the first method, as this will avoid the error and behave correctly.
// remove any duplicated values, leaving one entry.
public static void removeTheFirstNameDuplicates(HashMap<String, String> map) {
Map<K,V> map2 = invert(invert(map));
map.clear();
map.putAll(map2);
}
public static <K, V> Map<V, K> invert(Map<K, V> map) {
Map<V, K> map2 = new HashMap<>();
for(Map.Entry<K< V> entry: map.entrySet())
map2.put(entry.getValue(), entry.getKey());
return map2;
}
Your compiler will not produce a ConcurrentModifcationException. You should look at the line in in the stack track to see where you are modifying the collection while iterating over it e.g.
for (Map.Entry<String, String> pair: copy.entrySet())
{
if (pair.getValue().equals(value))
map.remove(pair.getKey());
}
In this case you are removing an entry while iterating. A simple solution is to use the Iterator directly. Usually you IDE can do this refactoring.
for (Iterator<String> iter = copy.values().iterator(); iter.hasNext();) {
if (iter.next().equals(value))
iter.remove();
}
The problem with this solution is this is called from a nested and it will remove ALL matching entries as it does in your code. i.e. it will remove all the entries.