Behavioral PatternBEGINNER6 min deep dive

Iterator Pattern Pattern

Lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, graph).

Real-World Mental Model / Metaphor:

A tour guide in a museum. The guide walks you through exhibits in a curated sequence (chronological, theme-based) without you needing to know the museum's private floorplan.

Interactive Runtime Simulator

Test and tweak inputs dynamically

Interactive Iterator Pattern SimulatorLIVE PLAYGROUND

Interact with the controls below to see how this design pattern executes in memory at runtime.

Category: Behavioral
Configure Chain Handlers (Toggle Failures):
CHAIN PIPELINE STATUS
Step 1: AuthHandler.check() -> PASSED
Step 2: RateLimitHandler.check() -> PASSED
Step 3: PayloadGuard.check() -> PASSED
The Problem It Solves

Exposing internal storage (e.g. array vs linked list vs binary tree) to clients who just want to loop through items.

The Architectural Solution

Extract traversal into a dedicated Iterator object with `hasNext()` and `next()` methods.

Pattern Structure & Participants

ParticipantRole & ResponsibilityType
Iterator (Interface)Declares hasNext() and next()interface
IterableCollectionDeclares createIterator()interface
ConcreteIteratorTracks current position and traverses collectionclass
Collaboration Rules:
  • Collection instantiates matching iterator
  • Client traverses collection through Iterator interface

Production Code Implementation

Iterator Pattern.java
public interface SimpleIterator<T> {
    boolean hasNext();
    T next();
}

public class NameRepository {
    public String[] names = {"Alice", "Bob", "Charlie", "Diana"};

    public SimpleIterator<String> getIterator() {
        return new NameIterator();
    }

    private class NameIterator implements SimpleIterator<String> {
        int index = 0;
        public boolean hasNext() { return index < names.length; }
        public String next() {
            if (this.hasNext()) return names[index++];
            return null;
        }
    }
}
When to Use:
  • •When your collection has a complex data structure under the hood, but you want to hide its complexity from clients.
  • •To reduce duplication of the traversal code across your app.
  • •When you want your code to be able to traverse different data structures using the same interface.
When to Avoid (Anti-Pattern):
  • •When working with simple lists where native language loops (`for`, `forEach`) are sufficient.

Staff Engineering Interview Insights & Gotchas

  • Explain how Iterator decouples traversal algorithms from graph/tree data structures.