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.
Application
The box keeps hundreds of results, more every month, and the podium only wants the three best athletes. Walk them one by one with a plain for loop, without loading everything into memory and without repeating the paging everywhere.
CoachLeaderboardControllerLoadEverythingLeaderboardresult table

In the earlier version, the request for the Fran top 3 reaches LoadEverythingLeaderboard, highlighted in red, which brings all 233 rows from the table.

OffsetLoopReport, highlighted in red, asks the table for limit 50 offset ? in a hand-written loop.

PagedResultIterator appears, highlighted, asking the table for the next page only when the current one runs out.

ResultHistory, highlighted, creates a new iterator for each walk.

Leaderboard, highlighted, asks ResultHistory for fastest("fran") and then the iterator for next().

The iterator, highlighted together with the table, has read only page 1.

GET /api/leaderboard/fran?top=3 travels from the coach to the controller, top("fran", 3) to Leaderboard, which asks the iterator for next() three times; it reads page 1. Leaderboard and the iterator are highlighted.

Inside the Spring context, JdbcClient, highlighted, hands out a Stream<Result>, also highlighted, that turns the table's rows into objects as they're consumed.

Final view: the coach, the controller, Leaderboard, ResultHistory, the iterator and the results table, all inside the Spring context.

Step 1 of 9

The Fran podium

The board shows the Fran podium: the three fastest athletes, each with their best time. There are 233 results stored, from about 90 athletes who repeat Fran often, and more every month.

The first version, LoadEverythingLeaderboard, loads all of them into a list, sorts them in memory and keeps the first ones. The test confirms it: it reads 233 rows to show 3.

Step 2 of 9

The paging, copied

The usual alternative is paging: ask for 50, then another 50… But look at OffsetLoopReport: the paging loop is written by hand, with its limit, its offset and its exit condition. And every report that needs to walk the results writes it again.

On top of that, offset 200 makes the database read and discard 200 rows on every page. And if a result arrives while you walk, a row is repeated; if one is deleted, another is lost.

Step 3 of 9

One by one

Iterator puts the walk inside an object with two questions:

  • hasNext(): is there anything left?
  • next(): give me the next one.

PagedResultIterator answers from a page in memory. When it runs out, it asks for the next one, and only then: "the next 50 after the last one I handed out", with (seconds, id) > (?, ?) so ties are settled by id. If a page comes back short, it knows it was the last; if it comes back full right at the end, one more, empty, query is needed to know.

Step 4 of 9

Something you can walk

ResultHistory doesn't return a list. It returns an Iterable<Result>: something that can hand out a new iterator every time someone starts walking it.

That's why two loops over the same fastest("fran") don't get in each other's way: each has its own iterator, starting from the beginning. iterator() is, in fact, a factory method: ResultHistory decides which concrete iterator gets created.

Step 5 of 9

A plain old for loop

Leaderboard walks with a plain for loop: under the hood, Java calls iterator(), hasNext() and next(). No pages, no SQL, no offsets.

It skips results from athletes already on the podium (each one appears once, with their best time) and, when it has what it needs, it leaves with break. It doesn't know in advance how many rows it'll need, and it doesn't have to: since the iterator only fetches pages on demand, leaving the loop also means reading stops.

Step 6 of 9

Only what's used

The test counts it: for the podium, with pages of 50, one page is read. Walking all 233 results reads five (50 + 50 + 50 + 50 + 33), and the last one, coming back short, saves one more query.

With the version that loaded everything, the podium cost every row. Now it costs as many pages as it takes to find three different athletes, usually one, whether the box has 233 results or 50,000. Other tests check that ties across pages are neither repeated nor lost.

Step 7 of 9

The podium through the API

GET /api/leaderboard/fran?top=3:

  1. LeaderboardController calls Leaderboard.top("fran", 3).
  2. The for loop asks the iterator for three results, and it reads the first page.
  3. The answer brings all three with their rank and time: first place, 2:31.

top goes from 1 to 100; outside that range, the answer is 400. A WOD with no results returns an empty list.

Step 8 of 9

Spring already does it for you

JdbcClient can hand you the results as a Stream: query(Result.class).stream(). Rows are turned into objects as you consume the stream, so limit(3) stops the mapping early. Whether the driver also fetches them from the database bit by bit depends on it (its fetch size, whether there's a transaction…): some bring everything at once anyway. And the stream keeps the connection and the ResultSet open until you close it: always use it in a try-with-resources.

A detail: with for and hasNext() you drive the loop (external iteration); with a Stream and its operations, the library drives it (internal iteration).

In Spring Data, repositories return Slice, Page or Stream, and since version 3.1 they have Window and WindowIterator, which walk results page by page "from the last position", like our iterator.

Step 9 of 9

Recap

You started loading 233 rows to show 3 and ended up with:

  • An iterator that hands out one at a time and fetches the next page only when needed.
  • An aggregate, ResultHistory, that hands out a new iterator for each walk.
  • A client that walks with a for loop and stops when it has enough.
  • Pages by key, "after the last one seen", instead of an offset.

Don't mix it up with its neighbours: Composite describes how the data is organised (a tree), and Iterator how to walk it without knowing that; Visitor helps you do different operations on each element you walk.

And when you don't need it: if the data is small and already in memory, a List and its for loop are simpler; and if you know how many rows you want and the filter fits in SQL, a LIMIT n in the query beats any iterator. A paging iterator pays off when you don't know how many rows you'll need and bringing everything is expensive.

Cheatsheet →

Code

LoadEverythingLeaderboard.java

public List<Result> top(String wod, int n) {
    List<Result> all = jdbc.sql("select id, athlete, wod, seconds from result where wod = ?")
        .param(wod).query(Result.class).list();               // every row of the WOD, in memory
    rowsRead = all.size();
    return all.stream().sorted(Comparator.comparingInt(Result::seconds)).limit(n).toList();
}

OffsetLoopReport.java

public int count(String wod) {
    int total = 0;
    for (int offset = 0; ; offset += 50) {                    // paging, by hand, here too
        List<Result> page = jdbc.sql("select id, athlete, wod, seconds from result where wod = ? "
                + "order by seconds, id limit 50 offset ?")
            .params(wod, offset).query(Result.class).list();
        if (page.isEmpty()) break;
        total += page.size();
    }
    return total;
}

PagedResultIterator.java

@Override
public boolean hasNext() {
    if (next < page.size()) return true;              // still something in this page
    if (noMorePages) return false;
    page = fetchAfter.apply(last, pageSize);          // fetch the next page only now
    next = 0;
    noMorePages = page.size() < pageSize;             // a short page is the last one
    return !page.isEmpty();
}

@Override
public Result next() {
    if (!hasNext()) throw new NoSuchElementException();
    last = page.get(next++);
    return last;
}

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));
}

Leaderboard.java

public List<Placing> top(String wod, int n) {
    if (n < 1 || n > 100) throw new InvalidLimitException();
    List<Placing> podium = new ArrayList<>();
    Set<String> placed = new HashSet<>();
    for (Result r : history.fastest(wod.toLowerCase(Locale.ROOT))) {   // no pages, no SQL
        if (!placed.add(r.athlete())) continue;                         // each athlete once: their best
        podium.add(Placing.of(podium.size() + 1, r));
        if (podium.size() == n) break;                                  // stop when there are enough
    }
    return podium;
}

ResultHistoryTest.java

ResultHistory history = new ResultHistory(jdbc, 50);
List<Result> podium = new ArrayList<>();
for (Result r : history.fastest("fran")) {
    podium.add(r);
    if (podium.size() == 3) break;                  // the loop decides when to stop…
}
assertThat(history.pagesFetched()).isEqualTo(1);    // …and only one page was ever read

LeaderboardApiTest.java

mvc.perform(get("/api/leaderboard/fran").param("top", "3"))
   .andExpect(status().isOk())
   .andExpect(jsonPath("$.length()").value(3))
   .andExpect(jsonPath("$[0].rank").value(1))
   .andExpect(jsonPath("$[0].time").value("2:31"));

SpringDoesItTooTest.java

List<Integer> podium;
try (Stream<Result> rows = jdbc.sql("select id, athlete, wod, seconds from result "
            + "where wod = ? order by seconds, id")
        .param("fran")
        .query(Result.class)
        .stream()) {                               // rows are mapped as the stream is consumed…
    podium = rows.limit(3).map(Result::seconds).toList();
}                                                  // …and closing it releases the ResultSet

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));
}

Quiz

1. How many pages does Leaderboard read for the Fran podium (top 3) with pages of 50?

2. What does the client gain from getting an Iterable instead of a List with every result?

3. Why are pages fetched "after the last result seen" and not with an offset?

4. What must you always do with the Stream that JdbcClient returns from stream()?

Cheatsheet →

Run it