Codectionary / Developer documentation / Java

Iterator

An Iterator provides a standard way to traverse a collection one element at a time without exposing its internal structure, using hasNext() to check for more elements and next() to retrieve the next one. Unlike a for-each loop, an Iterator's remove() method lets you safely delete elements from a collection while iterating over it - directly modifying a collection during a for-each loop throws a ConcurrentModificationException.

Syntax

Iterator<Type> it = collection.iterator();

Examples

Basic Iterator Usage

Manually stepping through a collection with hasNext() and next().

import java.util.ArrayList;
import java.util.Iterator;

ArrayList<String> names = new ArrayList<>();
names.add("John");
names.add("Zain");
names.add("Jamal");

Iterator<String> it = names.iterator();
while (it.hasNext()) {
    String name = it.next();
    System.out.println(name);
}

Safely Removing Elements While Iterating

The key advantage of Iterator over a for-each loop: safe removal during traversal.

import java.util.ArrayList;
import java.util.Iterator;

ArrayList<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= 10; i++) numbers.add(i);

Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
    int num = it.next();
    if (num % 2 == 0) {
        it.remove();  // safe removal - use it.remove(), not numbers.remove()
    }
}

System.out.println(numbers);  // [1, 3, 5, 7, 9]

Why a for-each Loop Cannot Safely Remove

Directly modifying a collection during a for-each loop throws an exception.

import java.util.ArrayList;

ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);

try {
    for (int num : numbers) {
        if (num == 2) {
            numbers.remove(Integer.valueOf(2));  // modifying during for-each
        }
    }
} catch (java.util.ConcurrentModificationException e) {
    System.out.println("Caught: " + e.getClass().getSimpleName());
}

Best practices

  • Use it.remove() through an Iterator when you need to delete elements while looping - never call collection.remove() directly inside a for-each loop
  • Use a for-each loop for simple read-only iteration - it is more concise than manually managing an Iterator
  • Use a ListIterator (available on List) instead of a plain Iterator when you also need to traverse backward or modify elements in place
  • Remember an Iterator becomes invalid ("fails fast") if the underlying collection is structurally modified by anything other than the iterator itself

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading