Browse Java Design Patterns & Enterprise Application Architecture

Implementing Iterator in Java

Implement Java iterators when custom aggregates need explicit traversal without exposing their internal representation.

Iterator: A pattern that provides stepwise access to a collection or aggregate without exposing its internal representation.

In Java, custom iterator work usually starts by implementing Iterable<T> so the aggregate integrates with the language naturally.

1public final class TaskQueue implements Iterable<Task> {
2    private final List<Task> tasks = new ArrayList<>();
3
4    @Override
5    public Iterator<Task> iterator() {
6        return tasks.iterator();
7    }
8}

That is enough for many cases. A custom iterator becomes interesting when traversal is not identical to the backing structure.

Good Reasons For A Custom Iterator

  • filtered traversal
  • tree or graph traversal
  • traversal over virtual or generated elements
  • domain-specific order

Review Rule

If the collection is already well-modeled by a standard Java collection, prefer that first. Custom iterators should exist because traversal meaning is special, not because patterns are fun.

Revised on Thursday, April 23, 2026