Sobes.tech
Senior

What happens if you try to delete the current element from a collection during a forEach iteration?

sobes.tech AI

Answer from AI

If during iteration over a collection using the forEach method you try to remove the current element from the same collection, the behavior depends on the type of collection and the implementation of forEach.

In standard Java collections, such as ArrayList, forEach uses an internal iterator, and modifying the collection during iteration (for example, removing an element) will lead to a ConcurrentModificationException.

Example:

List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
list.forEach(item -> {
    if (item.equals("b")) {
        list.remove(item); // will cause ConcurrentModificationException
    }
});

To safely remove elements during iteration, you should use an explicit iterator and its remove() method:

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String item = iterator.next();
    if (item.equals("b")) {
        iterator.remove(); // safe removal
    }
}