design patterns · behavioral

Iterator

Provides a way to sequentially access elements of a collection without exposing its underlying structure.

easybehavioral0.5h
Ask GPTConfidence

Pattern

Overview

Intent

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Real-World Analogy

A TV remote channel-up button - you iterate channels without knowing how they are stored internally.

When client code needs to traverse a collection without caring how it is stored (array, tree, hash), the Iterator pattern provides a uniform hasNext()/next() interface that works the same for any collection.

Iterator defines hasNext() and next(). The collection implements Iterable, returning a new Iterator instance. The iterator maintains a cursor position and advances it on each next() call. Java's for-each loop uses Iterator transparently.

When to use

Uniform traversal over different collection types - custom data structures, tree/graph traversal, lazy sequence generation.

When not to

Simple arrays or lists where a standard for loop is clearer. When you don't need to hide the collection structure.

Participants

IteratorConcreteIteratorAggregateConcreteAggregate

Key Insights

  • Java's Iterable/Iterator interfaces are a built-in implementation of this pattern
  • For-each loop syntax (for T item : collection) requires Iterable<T>
  • External iterators (client calls next()) vs internal iterators (collection calls a lambda) are two variants
  • Generators in Python and async iterators in JavaScript are Iterator pattern implementations