Behavioral 7 — Iterator
In one line
Provide sequential access over a collection without exposing its internals. Mostly baked into Java today — nested iterators (tree walks, pagination) still show up.
Think of it like this
A TV remote's 'next channel' button. You go through channels one by one without knowing how the TV stores its channel list.
Key ideas
- 01
Solves: traversal decoupled from data structure internals.
- 02
Java Iterable/Iterator; enhanced for-loop; streams cover most needs.
- 03
Interview angle: implement an iterator over a tree (BFS/DFS) — tests 'tell, don't ask'.
Java / Spring map
- →
java.util.Iterator; Stream.iterate; custom tree iterators.
Code & diagrams
A lazy in-order iterator over a binary tree. It uses O(height) memory and never builds a full list.
public final class InOrderIterator<T> implements Iterator<T> {
private final Deque<Node<T>> stack = new ArrayDeque<>();
public InOrderIterator(Node<T> root) { pushLeft(root); }
private void pushLeft(Node<T> n) {
while (n != null) { stack.push(n); n = n.left; }
}
@Override public boolean hasNext() { return !stack.isEmpty(); }
@Override public T next() {
if (!hasNext()) throw new NoSuchElementException();
Node<T> n = stack.pop();
pushLeft(n.right); // next smallest is the leftmost of the right subtree
return n.value;
}
}
// for (T v : (Iterable<T>) () -> new InOrderIterator<>(root)) { ... }Explain without notes
What would a lazy iterator over a huge CSV line-by-line give you?
Practice
Write an inorder Iterator<MenuItem> over the Composite menu tree.
Trade-offs
- ↔
Fail-fast iterators (ArrayList) throw ConcurrentModificationException if the list changes mid-loop; fail-safe ones (CopyOnWriteArrayList, ConcurrentHashMap) iterate over a snapshot or weakly consistent view.
Completion checklist
I can write a lazy tree iterator and explain fail-fast vs fail-safe.