Quick revision
The short answer
I would extend Spliterators.AbstractSpliterator and implement tryAdvance so that it hands out records from the current page and fetches the next page only when the current one is used up, then wrap it with StreamSupport.stream(spliterator, false). It reports ORDERED and NONNULL with an unknown size of Long.MAX_VALUE, and onClose releases any server-side cursor, so callers use it in try-with-resources. Stream.iterate(seed, hasNext, next) with flatMap is a shorter alternative for cursor-based pages; a plain Iterator works too but is clumsier.
What to remember
In this answer, we built a lazy stream over a paged REST API by extending Spliterators.AbstractSpliterator, with a tryAdvance that serves records from the current page and fetches the next page only when it runs out. We wrapped it with StreamSupport.stream(spliterator, false), reported ORDERED and NONNULL with an unknown size of Long.MAX_VALUE, and registered an onClose action so callers release server-side cursors with try-with-resources. We also saw that Stream.iterate with flatMap is a concise alternative that fetches the first page eagerly, and that an Iterator works but splits the logic awkwardly.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would extend Spliterators.AbstractSpliterator and implement tryAdvance so that it hands out records from the current page and fetches the next page only when the current one is used up, then wrap it with StreamSupport.stream(spliterator, false). It reports ORDERED and NONNULL with an unknown size of Long.MAX_VALUE, and onClose releases any server-side cursor, so callers use it in try-with-resources. Stream.iterate(seed, hasNext, next) with flatMap is a shorter alternative for cursor-based pages; a plain Iterator works too but is clumsier.
Why this question is asked
Paged APIs are everywhere: a CRM returns 100 customers per call, a payments provider returns transactions with a cursor, a search service scrolls through results. Code that loads every page into a list before processing wastes memory and time, especially when the caller only needs the first few matches. A lazy stream lets callers write ordinary filter and limit pipelines while we fetch pages on demand. Interviewers ask this to see whether we can build a correct custom stream source. In this answer, we will recap the API shape, write the Spliterator, see exactly when pages are fetched, compare the Iterator and Stream.iterate options, and handle closing.
1A Quick Recap of the Page API
Assume the REST API returns a page of records plus a cursor, a token that identifies the next page, or null when there are no more pages. Our client wraps the HTTP call in a small interface so the stream code does not care about HTTP details, and so tests can use a fake.
Laziness here means two things. We must not call fetch until a record from that page is actually needed. And once the stream stops pulling, because limit or findFirst has its answer, we must not fetch any more pages.
2Writing the Spliterator
Spliterators.AbstractSpliterator is a base class that already implements trySplit (by batching, which we will not rely on), so we only write the constructor and tryAdvance.
Notice the while loop. A page can legitimately be empty while a cursor is still present, which some APIs return after filtering on the server, so we keep fetching until we find a record or reach the last page. The characteristics are honest: ORDERED because the API returns records in a defined order, NONNULL because records are never null, and size Long.MAX_VALUE because we do not know the total. If the API reports a total count, we could pass it as an estimate, but we must not claim SIZED unless it is exact.
We pass false to StreamSupport.stream, making the stream sequential. A paged API is inherently sequential, because page 2's cursor comes from page 1, so parallel splitting would only batch records already fetched and add risk.
3When Pages Are Fetched
Here is what happens with a caller that wants the first five VIP customers, with 100 customers per page.
9 messages in order. Play them, or step through them one at a time.
Page 3 is never requested because the stream stops asking.
The terminal toList pulls elements through limit and filter, which call tryAdvance on our Spliterator one element at a time. The first call fetches page 1. Calls 2 to 100 come from memory. The 101st call fetches page 2. When the fifth VIP arrives, limit signals that it is satisfied, the stream stops calling tryAdvance, and page 3 is never requested.
4The Alternatives: Iterator and Stream.iterate
An Iterator works with Spliterators.spliteratorUnknownSize(iterator, ORDERED | NONNULL), but it is clumsier. hasNext() must answer whether a record exists, which means it has to fetch the next page itself and remember it, while next() must also handle being called without hasNext(). That splits one piece of logic across two methods with shared state. tryAdvance does both in one place, which is why it is the more natural fit.
Since Java 9, Stream.iterate(seed, hasNext, next) can walk the pages themselves, and flatMap turns pages into records.
This is short and lazy for later pages: iterate computes the next page only when flatMap needs another one, and since JDK 10, flatMap stops pulling as soon as limit is satisfied. There is one catch: the seed is evaluated immediately, so page 1 is fetched when we build the stream, not when the terminal operation runs. That matters if the stream is created in one place and consumed later, or not at all. Wrapping the seed in a lazily evaluated step, or using the Spliterator, avoids it.
5Closing Resources
Many paged APIs hold state on the server. Search services with scroll cursors and databases with server-side cursors keep resources open until we release them or they time out. Streams have a hook for this: onClose registers an action that runs when the stream's close() method is called. Streams do not close themselves when the terminal operation finishes, so the caller must use try-with-resources, as in the earlier example.
We should document that requirement on the method, the same way Files.lines documents it, and in code review treat a PagedStreams.of call outside try-with-resources as a bug. For APIs with no server-side state, release() does nothing, and forgetting to close is harmless, but keeping the habit means the code stays correct if the API changes.
6Follow-up questions
How would you test this without calling the real API?
Pass a fake PageSource that serves fixed pages from memory and counts calls to fetch. Then assert, for example, that limit(5) over VIPs on pages 1 and 2 results in exactly two calls, that empty pages with a cursor are skipped, that an empty first page with no cursor gives an empty stream, and that closing the stream calls release once.
What happens if a page fetch fails halfway through?
The exception from fetch propagates out of tryAdvance and out of the terminal operation, and the try-with-resources still calls close, so release runs. If transient failures are expected, retry inside fetch with a small bounded backoff rather than in the stream, so the Spliterator's state, the cursor, stays consistent.
Could this stream be made parallel?
Not usefully. Each cursor comes from the previous page, so pages cannot be fetched independently. If the API supports offset-based pages and a known total, a Spliterator could split by page ranges, but parallel streams on the common pool should not do blocking HTTP anyway; for concurrent fetching we would use an explicit executor.
7Conclusion
In this answer, we built a lazy stream over a paged REST API by extending Spliterators.AbstractSpliterator, with a tryAdvance that serves records from the current page and fetches the next page only when it runs out. We wrapped it with StreamSupport.stream(spliterator, false), reported ORDERED and NONNULL with an unknown size of Long.MAX_VALUE, and registered an onClose action so callers release server-side cursors with try-with-resources. We also saw that Stream.iterate with flatMap is a concise alternative that fetches the first page eagerly, and that an Iterator works but splits the logic awkwardly.
Open with
I would write a Spliterator, extending Spliterators.AbstractSpliterator so I only need tryAdvance. It keeps an iterator over the current page, the next cursor and a flag for whether the last page was loaded.
Then, if they want more
In tryAdvance, while the current page has nothing left, it returns false if the last page was already loaded, otherwise it fetches the next page with the cursor; then it hands one record to the action and returns true. The loop also skips empty pages.
I construct it with Long.MAX_VALUE as the size, since the total is unknown, and ORDERED and NONNULL as characteristics; I would not claim SIZED. Then StreamSupport.stream(spliterator, false) gives a sequential stream, because each cursor depends on the previous page.
The laziness is the point: with filter and limit(5), the stream stops calling tryAdvance once it has five matches, so if they are on the first two pages, we make exactly two HTTP calls. I add onClose to release any server-side cursor and document that callers must use try-with-resources.
Stream.iterate with a hasNext predicate, from Java 9, plus flatMap over page items, also works and is shorter, but it fetches the first page as soon as the stream is built. An Iterator works too, but hasNext has to prefetch, so the logic is split across two methods.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 10, Java 9
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.stream, package documentation, java.util.function, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a Stream that reads records from a paged REST API lazily, fetching the next page...": https://scrivio-interview-library.netlify.app/java/streams/2dc9301e18/