java - How to remove multiple mappings in hashmap without ConcurrentModificationException?

问题描述:

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.

As @Ejp suggested , Iterator#remove() is the optimal solution to get rid of ConcurrentModificationException.

A similar kind of post here Iterating through a list, avoiding ConcurrentModificationException when removing in loop.

Also with java8 , you can very well use removeIf() method . Have a look at Iterating through a list, avoiding ConcurrentModificationException when removing in loop

网友答案:

So the key point here is not to change the size of the hashmap while iterating. Thus instead of deleting the entry within the loop, I added the key in an arraylist. And when the loop got over, I traversed through that arraylist and deleted the entries of the hashmap corresponding to the key in the arraylist.