Back to course

Traversing Collections using Iterators and the Enhanced for Loop

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 41: Traversing Collections using Iterators

There are several ways to loop over collections, each with different capabilities.

1. The Enhanced for Loop (For-Each)

This is the simplest way to iterate through any collection (List, Set, or Map keys/values) that implements the Iterable interface. It is read-only and highly recommended for simplicity.

java List planets = List.of("Mars", "Earth", "Jupiter");

for (String planet : planets) { System.out.println(planet); }

2. The Iterator Interface

All Collection classes provide an iterator() method that returns an Iterator object. This is the only way to safely remove elements from a collection while iterating over it.

Key Iterator Methods

  • hasNext(): Returns true if there are more elements.
  • next(): Returns the next element and advances the iterator.
  • remove(): Removes the element that was last returned by next().

java import java.util.Iterator;

List numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); Iterator it = numbers.iterator();

while (it.hasNext()) { Integer num = it.next(); if (num % 2 == 0) { it.remove(); // Safe removal } }

System.out.println(numbers); // Output: [1, 3, 5]

Concurrency Issue (Fail-Fast): If you try to modify a collection (add/remove) inside a standard for loop or an enhanced for loop, Java will throw a ConcurrentModificationException. The Iterator.remove() method is the safe way to modify a collection during iteration.