Iterator Pattern
Walk through the items of a collection one at a time without knowing, or depending on, how the collection stores them.
Overview
The Iterator pattern is one of the behavioral patterns in Design Patterns (Gamma, Helm, Johnson and Vlissides, 1994). A collection keeps its items in some structure: an array, a linked list, a tree, a hash table, a page of results from an API. The pattern moves the job of walking that structure out of the collection and out of the caller, into a small object that knows where it is and how to take the next step. The caller asks that object for the next item until there are none left.
The pattern is so useful that most languages built it in. Python's for loop, Java's enhanced for and JavaScript's for...of all call an iterator behind the scenes. Interviewers ask about Iterator to see whether you understand what the loop is doing, whether you can write an iterator for a structure the language does not know (a tree, a graph, a paginated API), and whether you know what goes wrong when a collection changes during a walk.
The problem it solves
Without an iterator, code that walks a collection has to know how the collection is built. A caller that indexes into an array breaks when the collection becomes a linked list; a caller that recurses over a tree cannot be reused for a graph. The collection also has to expose its insides so callers can walk them, which means callers can change them by accident.
The pattern changes four things. Without it, the caller knows the structure (an index, a next pointer, child links); with it, the caller knows only two operations: is there more, and give me the next one. Without it, every caller carries one walking routine per structure; with it, there is one iterator per structure, written once. Without it, the collection exposes its internal list or nodes; with it, the collection stays sealed and only the iterator sees inside. And without it, two walks at once need two sets of bookkeeping in the caller, while with it each iterator holds its own position, so many walks can be in flight.
Interview questions
- Write an iterator that returns the values of a binary search tree in sorted order, one at a time.
- What happens if you change a collection while iterating over it?
- What is the difference between external and internal iteration?
- Design an iterator over a paginated API.
- Why does the collection create the iterator instead of the caller?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio