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.
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
| Java | Python | JavaScript | |
|---|---|---|---|
| Collection side | Iterable<T>.iterator() | __iter__() | [Symbol.iterator]() |
| Iterator side | hasNext(), next() | __next__(), raises StopIteration | next() returns { value, done } |
| Loop | for (T x : coll) | for x in coll: | for (const x of coll) |
| Generator shortcut | — | yield | function* / 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 orderclass BST:
def __iter__(self):
# A generator function IS an iterator factory: Python writes the state machine for you
stack, node = [], self.root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
yield node.val
node = node.right
for x in tree:
print(x)
# Recursive generators compose with 'yield from'
def inorder(node):
if node:
yield from inorder(node.left)
yield node.val
yield from inorder(node.right)class BST<T> {
root?: Node<T>;
*[Symbol.iterator](): IterableIterator<T> { // generator method
const stack: Node<T>[] = [];
let node = this.root;
while (stack.length || node) {
while (node) { stack.push(node); node = node.left; }
node = stack.pop()!;
yield node.val;
node = node.right;
}
}
}
for (const x of tree) console.log(x);
const firstThree = [...tree].slice(0, 3);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))Stream.iterate(new long[]{0, 1}, f -> new long[]{f[1], f[0] + f[1]})
.map(f -> f[0])
.limit(10)
.forEach(System.out::println);
try (Stream<String> lines = Files.lines(Path.of("huge.log"))) { // lazy
lines.filter(l -> l.contains("ERROR")).limit(100).forEach(System.out::println);
}function* fibonacci() {
let [a, b] = [0, 1];
while (true) { yield a; [a, b] = [b, a + b]; }
}
function* take<T>(it: Iterable<T>, n: number) {
for (const x of it) { if (n-- <= 0) return; yield x; }
}
console.log([...take(fibonacci(), 10)]);
// Async iterators: paginated APIs look like simple loops
async function* allUsers() {
let cursor: string | undefined;
do {
const page = await fetchPage(cursor);
yield* page.items;
cursor = page.nextCursor;
} while (cursor);
}
for await (const u of allUsers()) process(u);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 raisesRuntimeErrorfor dicts that change size. Useiterator.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, generatorfinally).
- Iterator gives uniform sequential access, hiding the collection's structure.
- Every major language builds
forloops 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.