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
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(): Returnstrueif there are more elements.next(): Returns the next element and advances the iterator.remove(): Removes the element that was last returned bynext().
java import java.util.Iterator;
List
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.