This question already has an answer here:
I was doing:
for (Object key : map.keySet())
if (something)
map.remove(key);
which threw a ConcurrentModificationException, so i changed it to:
for (Object key : new ArrayList<Object>(map.keySet()))
if (something)
map.remove(key);
this, and any other procedures that modify the map are in synchronized blocks.
is there a better solution?
if no one comes up with a better solution, first to say no gets the tick ;)
Maybe you can iterate over the map looking for the keys to remove and storing them in a separate collection. Then remove the collection of keys from the map. Modifying the map while iterating is usually frowned upon. This idea may be suspect if the map is very large.
ConcurrentHashMap
You can use
java.util.concurrent.ConcurrentHashMap
.It implements
ConcurrentMap
(which extends theMap
interface).E.g.:
This approach leaves your code untouched. Only the
map
type differs.Java 8 support a more declarative approach to iteration, in that we specify the result we want rather than how to compute it. Benefits of the new approach are that it can be more readable, less error prone.
And result is as follows:
Well, there is, definitely, a better way to do so in a single statement, but that depends on the condition based on which elements are removed.
For eg: remove all those elements where
value
is test, then use below:UPDATE It can be done in a single line using Lambda expression in Java 8.
I know this question is way too old, but there isn't any harm in updating the better way to do the things :)
An alternative, more verbose way
As of Java 1.8 you could do this using with: