I'm trying to remove elements from a set (someObjectSet) while looping through it. As I googled, using removeIf should avoid ConcurrentModificationException in this case. However this doesn't work for me.
Did google lie to me (or I misundertood it), or I'm not using removeIf correctly?
Set<SomeObject> someObjectSet = new HashSet<>();
someObjectSet.add(obj1);
someObjectSet.add(obj2);
someObjectSet.add(obj3);
for (SomeObject obj : someObjectSet ){
...
someObjectSet.removeIf(ele -> if ele satisfies some condition)
}
The reason I want to do removeif inside the loop is that, in each loop, it can be determined that some other elements of the set no longer need to go in the loop, therefore I’m removing it so that the for loop won’t pick them up again.
For example,
In loop1, obj1 gets picked.
Then in the same loop it finds out obj2 no longer needs to be processed => remove obj2 from the set.
In loop2, instead of obj2, obj3 is picked up
Thanks in advance!