How to modify a Collection while iterating using for-each loop without ConcurrentModificationException? [duplicate]

Use Iterator#remove.

This is the only safe way to modify a collection during iteration. For more information, see The Collection Interface tutorial.

If you also need the ability to add elements while iterating, use a ListIterator.


One work around is to save your changes and add/remove them after the loop.

For example:

List<Item> toRemove = new LinkedList<Item>();

for(Item it:items){
    if(remove){
        toRemove.add(it);
    }
}
items.removeAll(toRemove);