dabadaba dabadaba - 5 months ago 9x
Java Question

Removing item from a collection safely with Java 8

I was trying to iterate a collection using

but realized calling
remove(Object o)
on that very collection was not safe and could cause a
. 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))

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?


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));