Skip to content
Preptima
mediumConceptCodingEntryMidSenior

How do you remove elements from a collection while iterating it, and what makes an iterator fail-fast?

Structural modification through the collection during a for-each invalidates the iterator, which detects it by comparing a modification counter and throws ConcurrentModificationException. Remove through the iterator, or use removeIf, or pick a collection whose iterator is weakly consistent instead.

5 min readUpdated 2026-08-15

Answer

Short answer

In Java, remove elements while iterating by using Iterator.remove(), Collection.removeIf(...), or a collection whose iterator is designed for concurrent changes. Removing through the collection inside a for-each loop changes the collection's structure behind the iterator, so fail-fast iterators usually throw ConcurrentModificationException. That exception is a bug detector, not a correctness guarantee.

Was this answer helpful?

Likely follow-ups

  • Why does removing the second-to-last element of an ArrayList in a for-each sometimes not throw?
  • What does the iterator of ConcurrentHashMap guarantee about entries added after iteration begins?
  • Why does CopyOnWriteArrayList's iterator not support remove?
  • How would you safely remove entries from a Map while iterating it?

Related questions

Further reading

Related Topics