Iterator
Also known as: Cursor
Traverse the elements of a collection without exposing its internal representation (list, tree, paginated API…).
- 10 animated steps
- 6 languages
- Behavioral patterns
The problem
An API returns users in pages of 100. Every piece of client code has to deal with page numbers, buffers and the stop condition: pagination logic leaks everywhere.
The solution
Encapsulate the traversal in an iterator (next() / hasNext() or a generator). The client writes a plain for loop; the iterator loads pages on demand.
The pattern in action
- Client
- Key role of the pattern
- Object
- Data or state
- The client asks for the next element, nothing more.
- Empty buffer: the iterator loads a page.
- API /users → UserIterator [ ]: [u1, u2, u3]
- UserIterator [u1, u2, u3] → Client (for…of): u1
- Client (for…of) → UserIterator [u2, u3]: next()
- Served from the buffer, with no network call.
- Client (for…of) → UserIterator [u3]: next()
- UserIterator [u3] → Client (for…of): u3
- Client (for…of) → UserIterator [ ]: next()
- Buffer exhausted: next page. The client never saw the pagination.
An analogy
The "next channel" button on a remote control: you move forward without knowing the internal list of frequencies.
When to use it
- Complex collections (trees, graphs)
- Pagination, streaming, database cursors
- Lazy traversal of large data sets
Pros and cons
Pros
- The client knows nothing about the internal structure
- Several traversals can run at the same time
- Lazy evaluation → memory under control
Cons
- Overkill for a plain list
- Handling network errors in the middle of an iteration
Implementations
The same example, written idiomatically in each language.
Iterator in Python
from collections.abc import Iterator
def users(api) -> Iterator[dict]:
"""Generator: iterates over all pages transparently."""
page = 1
while True:
batch = api.get("/users", page=page)
if not batch:
return
yield from batch
page += 1
for user in users(api): # the client is unaware of pagination
print(user["email"])
Iterator in TypeScript
async function* users(api: Api): AsyncGenerator<User> {
for (let page = 1; ; page++) {
const batch = await api.get<User[]>("/users?page=" + page);
if (batch.length === 0) return;
yield* batch;
}
}
for await (const u of users(api)) {
console.log(u.email); // pagination is invisible to the client
}
Iterator in Java
class UserIterator implements Iterator<User> {
private final Api api;
private int page = 1;
private Deque<User> buffer = new ArrayDeque<>();
UserIterator(Api api) { this.api = api; }
@Override
public boolean hasNext() {
if (buffer.isEmpty()) buffer = new ArrayDeque<>(api.getUsers(page++));
return !buffer.isEmpty();
}
@Override
public User next() {
if (!hasNext()) throw new NoSuchElementException();
return buffer.poll();
}
}
Iterable<User> all = () -> new UserIterator(api);
for (User u : all) System.out.println(u.email());
Iterator in C#
async IAsyncEnumerable<User> Users(Api api)
{
for (var page = 1; ; page++)
{
var batch = await api.GetUsersAsync(page);
if (batch.Count == 0) yield break;
foreach (var u in batch) yield return u;
}
}
await foreach (var u in Users(api))
Console.WriteLine(u.Email);
Iterator in PHP
function users(Api $api): Generator
{
for ($page = 1; ; $page++) {
$batch = $api->get('/users', ['page' => $page]);
if ($batch === []) {
return;
}
yield from $batch;
}
}
foreach (users($api) as $user) {
echo $user['email'], PHP_EOL;
}
// Laravel: User::lazy() and User::cursor() apply the same principle
Iterator in Go
// Go 1.23+: native iterators with iter.Seq
func Users(api *Api) iter.Seq[User] {
return func(yield func(User) bool) {
for page := 1; ; page++ {
batch := api.GetUsers(page)
if len(batch) == 0 {
return
}
for _, u := range batch {
if !yield(u) {
return // the client did a "break"
}
}
}
}
}
for u := range Users(api) {
fmt.Println(u.Email)
}
Frequently asked questions
What is the Iterator design pattern?
Traverse the elements of a collection without exposing its internal representation (list, tree, paginated API…). Encapsulate the traversal in an iterator (next() / hasNext() or a generator). The client writes a plain for loop; the iterator loads pages on demand.
When should you use the Iterator pattern?
Complex collections (trees, graphs); Pagination, streaming, database cursors; Lazy traversal of large data sets.
What are the pros and cons of the Iterator pattern?
Pros: The client knows nothing about the internal structure; Several traversals can run at the same time; Lazy evaluation → memory under control. Cons: Overkill for a plain list; Handling network errors in the middle of an iteration.