Java ยท Chapter 36 of 42

Java Iterators

An Iterator provides a standard way to traverse elements of a collection one at a time, using hasNext() to check for more elements and next() to retrieve the next one.

Iterators also allow safe removal of elements during iteration via remove(), which is not safe to do with a regular for-each loop (it throws ConcurrentModificationException).

Syntax
Iterator<Type> it = collection.iterator();
while (it.hasNext()) {
  Type item = it.next();
}

Using Iterator

Call iterator() on a collection to get an Iterator, then loop with while (it.hasNext()) { it.next(); }.

Removing during iteration

Iterator.remove() safely removes the current element during iteration, avoiding ConcurrentModificationException that occurs when modifying a collection inside a for-each loop.

Example 1 (java)
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<Integer> nums = new ArrayList<>(List.of(1, 2, 3));
    Iterator<Integer> it = nums.iterator();
    while (it.hasNext()) {
      int n = it.next();
      if (n == 2) it.remove();
    }
    System.out.println(nums);
  }
}
Output
[1, 3]

The Iterator safely removes 2 from the list while iterating.

Key points

  • hasNext() checks if more elements remain.
  • next() retrieves and advances to the next element.
  • Iterator.remove() safely removes elements during iteration.
  • Modifying a collection directly in a for-each loop can throw ConcurrentModificationException.
๐Ÿ’ก Note: Use Iterator.remove() instead of collection.remove() when deleting elements while looping.

๐Ÿ“ Quick Quiz

1. What method checks if more elements remain?

2. What can happen if you modify a List directly inside a for-each loop?

3. What method safely removes the current element during iteration?