Cheatsheet

Iterator

Intent

Give a way to walk through a collection's elements one by one without showing how they're stored, so whoever walks them doesn't depend on those details.

Structure (UML)

Spring contextCoachResultHistoryLeaderboardControllerLeaderboardPagedResultIteratorresult table

Participants

  • Iterator (Iterator<Result>), with hasNext() and next()
  • ConcreteIterator (PagedResultIterator), which knows how to ask for the next page when needed
  • Aggregate (Iterable<Result>), something that can be walked
  • ConcreteAggregate (ResultHistory), which hands out a new iterator for each walk
  • Client (Leaderboard), which walks with a for loop and stops when it has enough

ResultHistory.java

/** Every result of a WOD, fastest first. Each for-each loop gets its own iterator. */
public Iterable<Result> fastest(String wod) {
    return () -> new PagedResultIterator(pageSize, (after, size) -> page(wod, after, size));
}

Pros

  • The client walks with a for loop, knowing nothing about pages or SQL
  • Only what's used is read; if the loop stops early, no more pages are fetched
  • The paging lives in one place instead of being copied into every report

Cons

  • A long walk runs several queries and may see data that changes meanwhile
  • There's no direct access to a position, nor a total size, without walking it all
  • Getting hasNext() and next() right (without skipping or repeating elements) is trickier than it looks

← Iterator · Run it