Iterating Collections in Java
Every standard collection can be walked in more than one way, and the differences matter once modification enters the picture. A for-each loop is the simplest option for read-only iteration; calling an explicit Iterator manually allows safely removing elements mid-traversal through the iterator's own remove() method, something a for-each loop cannot do safely at all; and forEach(lambda), from Java 8 onward, applies an action to every element in one expression.
Modifying a collection's structure — adding or removing elements — through any means other than the active iterator's own remove() method while a for-each or Iterator loop is in progress throws a ConcurrentModificationException. That's a safety check the collection performs specifically to catch this class of bug early, rather than let it corrupt state silently.
for-each for read-only iteration
The simplest option whenever elements just need to be visited, not removed.
Iterator, explicitly
Obtained via collection.iterator(), offering hasNext() and next() manually, plus a genuinely safe remove() during traversal.
Safe removal during iteration
Only the active iterator's own remove() method is safe to call mid-loop; calling the collection's remove() directly during a for-each is not.
ConcurrentModificationException
Thrown when a collection's structure changes during iteration through any means besides that iterator's own remove(), catching the bug immediately rather than letting it corrupt state silently.
forEach(lambda)
Applies a given action to every element in one expression, a concise alternative to a full loop when nothing needs to be removed.
import java.util.ArrayList;import java.util.Iterator; public class IterateDemo { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.add(3); Iterator<Integer> it = numbers.iterator(); while (it.hasNext()) { if (it.next() == 2) { it.remove(); } } System.out.println(numbers); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.