dabadaba dabadaba - 6 months ago 10
Java Question

Removing item from a collection safely with Java 8

I was trying to iterate a collection using

forEach
but realized calling
remove(Object o)
on that very collection was not safe and could cause a
ConcurrentModificationException
. This is what I was trying to do:

public void removeMatchup(Set<Player> players) {
predefinedMatchups.stream().filter(m -> m.getPlayers().equals(players)).forEach(m -> predefinedMatchups.remove(m));
}


So I had it changed to this:

public void removeMatchup(Set<Player> players) {
Iterator<Matchup> iterator = predefinedMatchups.iterator();
while (iterator.hasNext())
if (iterator.next().getPlayers().equals(players))
iterator.remove();
}


I really like how concise streams are, that's why I am reworking my whole project to include Java 8's new features.

Is there a workaround for this problem where I could use streams while performing safe deletions?

Answer

Since Set is Collection it inherits removeIf(Predicate<? super E> filter) method.

So your code can look like:

public void removeMatchup(Set<Player> players) {
    predefinedMatchups.removeIf(m -> m.getPlayers().equals(players));
}
Comments