Iterator

Traversing a collection without exposing its representation — external vs internal iteration, Java Iterator/Iterable, Python's iterator protocol and generators, JavaScript's Symbol.iterator, lazy and infinite sequences.

Beginner 2 min readLesson 19 of 24

Intent: provide a way to access the elements of a collection sequentially without exposing its underlying representation.

A list, a tree, a hash map, a database cursor, a paginated API, and a stream of lines from a file are stored very differently, but code that consumes them just wants "give me the next one until there are no more". The iterator is that uniform interface — and it's built into every modern language's for loop.

The protocol in three languages

JavaPythonJavaScript
Collection sideIterable<T>.iterator()__iter__()[Symbol.iterator]()
Iterator sidehasNext(), next()__next__(), raises StopIterationnext() returns { value, done }
Loopfor (T x : coll)for x in coll:for (const x of coll)
Generator shortcut—yieldfunction* / yield

Writing an iterator: tree traversal

An in-order traversal of a binary search tree, without exposing nodes, and lazy (one step at a time, using an explicit stack — O(h) memory):

class BST<T extends Comparable<T>> implements Iterable<T> {
    private record Node<T>(T val, Node<T> left, Node<T> right) {}
    private Node<T> root;

    @Override
    public Iterator<T> iterator() {
        return new Iterator<>() {
            private final Deque<Node<T>> stack = new ArrayDeque<>();
            { pushLeft(root); }                                  // initialiser

            private void pushLeft(Node<T> n) {
                while (n != null) { stack.push(n); n = n.left(); }
            }
            public boolean hasNext() { return !stack.isEmpty(); }
            public T next() {
                if (!hasNext()) throw new NoSuchElementException();
                Node<T> n = stack.pop();
                pushLeft(n.right());
                return n.val();
            }
        };
    }
}

for (int x : tree) System.out.println(x);                       // sorted order

Lazy and infinite sequences

Iterators produce values on demand, so they can represent sequences too large for memory — or infinite:

from itertools import islice, count

def fibonacci():
    a, b = 0, 1
    while True:                           # infinite, but lazy
        yield a
        a, b = b, a + b

print(list(islice(fibonacci(), 10)))      # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

# Pipelines process one item at a time with constant memory
lines = (l for l in open("huge.log"))
errors = (l for l in lines if "ERROR" in l)
first_100 = list(islice(errors, 100))

External vs internal iteration

  • External: the client drives (while (it.hasNext()) it.next()), so it can stop early, interleave two iterators, etc.
  • Internal: the collection drives and calls your function (list.forEach(fn), streams). Less control, but the library can optimise (parallel streams).

Pitfalls

  • Concurrent modification: changing a collection while iterating it. Java's fail-fast iterators throw ConcurrentModificationException; Python raises RuntimeError for dicts that change size. Use iterator.remove(), iterate over a copy, or collect changes and apply after.
  • Single use: Python iterators and generators are exhausted after one pass — iterate a generator twice and the second loop does nothing. Iterables (lists) create fresh iterators each time.
  • Resource cleanup: iterators over files or cursors need closing (try-with-resources, with, generator finally).
Key takeaways
  • Iterator gives uniform sequential access, hiding the collection's structure.
  • Every major language builds for loops on an iterator protocol.
  • Generators (yield) are the easiest way to write iterators.
  • Iterators are lazy: they handle huge, streaming and infinite sequences in constant memory.
  • Don't modify a collection while iterating; generators are single-use.