I have 2 hashmaps: HashMap<String, Word> hmSmall, hmBig
. The mapping in each is many-to-one. Hence based on some criteria, I have to remove all the mappings corresponding to a particular value in both hashmaps. And for that, I am following this answer.
The problem is that I still get ConcurrentModificationException
while iterating over the hashmap.
Here is the code:
for (Iterator<Word> it = hmSmall.values().iterator(); it.hasNext(); i++) {
Word value = it.next();//java.util.ConcurrentModificationException here
String key = value.getKey();
if (hmBig.containsKey(key)) {
// if big contains less then remove from big
// else it.remove
if (hmBig.get(key).getTotalOccurances() < value
.getTotalOccurances()) {
hmBig.values().removeAll(
Collections.singleton(hmBig.get(key)));
} else {
// it.remove(); not using this based on https://stackoverflow.com/a/30214164/848377
hmSmall.values().removeAll(Collections.singleton(value));
}
}
}
Is there simple way out?