Command Palette

Search for a command to run...

PHASE 2Beginner ~6 min· topic 19 of 22Behavioral

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.

0/22 · 0%

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

  1. 01

    Solves: traversal decoupled from data structure internals.

  2. 02

    Java Iterable/Iterator; enhanced for-loop; streams cover most needs.

  3. 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

TreeIterator.javajava

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

01

What would a lazy iterator over a huge CSV line-by-line give you?

Practice

01

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.

Back to phase