Common Ways to Iterate

MethodWhen to Use
for-each loopSimple read-only iteration
IteratorWhen you need to remove items safely
ListIteratorBi-directional iteration (only for List)
for loop (index)Index-based control (only for List)
Streams / forEach()Modern, functional style (Java 8+)

Example

for-each loop
// Can't safely remove items using this method.
List<String> names = List.of("A", "B", "C");
 
for (String name : names) {
    System.out.println(name);
}
Iterator
// Avoids ConcurrentModificationException.
List<String> names = new ArrayList<>(List.of("A", "B", "C"));
Iterator<String> it = names.iterator();
 
while (it.hasNext()) {
    String name = it.next();
    if (name.equals("B")) {
        it.remove(); // safe removal
    }
}
ListIterator
// Can iterate both directions, modify in-place.
List<String> list = new ArrayList<>(List.of("A", "B", "C"));
ListIterator<String> lit = list.listIterator();
 
while (lit.hasNext()) {
    String val = lit.next();
    if (val.equals("B")) {
        lit.set("Z"); // Replaces "B" with "Z"
    }
}
forEach
// Can't remove or modify elements inside forEach() directly.
list.forEach(item -> System.out.println(item));
ConcurrentModificationException
// Occurs when a collection is modified during 
// iteration using methods other than Iterator.remove().
for (String s : list) {
    list.remove(s); // will throw exception
}

Best Practices

  • Use Iterator.remove() when modifying during iteration.
  • Use ListIterator if you need both forward and backward access.
  • Avoid modifying for-each or forEach() lambda.
  • Prefer modern for-each or streams when you don’t need to mutate.

Tip

Be ready to:

  • safely remove elements from list during iteration,
  • explain difference between Iterator and ListIterator,
  • talk about ConcurrentModificationException and how to avoid it.

Parent: _Collections