Quick revision
The short answer
The iterator keeps a buffer with the current page of customers and the next-page token; hasNext() fetches the next page only when the buffer is empty and a token is still available, looping past empty pages, and next() takes from the buffer or throws NoSuchElementException. Nothing is fetched in the constructor, remote failures are rethrown as unchecked exceptions with context, and the class is documented as not thread-safe. To expose it as a Stream, wrap it with StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false).
What to remember
In this answer, we built a lazy paging iterator over a REST API. It keeps a buffer of the current page and the next token, fetches inside hasNext() only when the buffer is empty and more pages exist, loops past empty pages, and lets next() take from the buffer or throw NoSuchElementException. It does no work in the constructor, turns IOException into an UncheckedIOException with the token as context, and is documented as not thread-safe. Wrapping it with Spliterators.spliteratorUnknownSize and StreamSupport.stream gives a lazy sequential Stream in which limit stops further requests.
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.
The iterator keeps a buffer with the current page of customers and the next-page token; hasNext() fetches the next page only when the buffer is empty and a token is still available, looping past empty pages, and next() takes from the buffer or throws NoSuchElementException. Nothing is fetched in the constructor, remote failures are rethrown as unchecked exceptions with context, and the class is documented as not thread-safe. To expose it as a Stream, wrap it with StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false).
Why this question is asked
Most real APIs return large result sets in pages: a list endpoint gives us 100 customers and a token that says where the next page starts. Callers do not want to deal with tokens; they want to loop over customers. Wrapping the paging in an Iterator is the classic way to hide it, and interviewers like this exercise because it tests several things at once: laziness, edge cases, the exact contract of Iterator, error handling over a network, and how iterators connect to streams. In this answer, we will define the API shape, write the iterator step by step, walk through the edge cases that usually go wrong, and then expose the result as a lazy Stream.
1The API and the Contract We Must Honour
Assume a client class wraps the HTTP call. It takes a page size and a token, and returns one page with the customers and the token for the next page, which is null on the last page. The first request is made with a null token.
The Iterator interface has a small but strict contract. hasNext() returns true if another element exists and may be called any number of times without moving forward. next() returns the next element and must throw NoSuchElementException when there is none. Callers are allowed to call next() without calling hasNext() first, and to call hasNext() twice in a row, so our state handling must be correct in both cases.
Laziness means we fetch a page only when a caller actually needs an element from it. If the caller stops after the first 30 customers, we must have made exactly one request.
2Writing the Iterator
The state is a buffer of customers from the current page, the token for the next page, and a flag that tells us whether we have made the first request yet. The flag is needed because a null token means two different things: before the first call it means start from the beginning, after a call it means there are no more pages.
8 messages in order. Play them, or step through them one at a time.
A request is made only when the buffer runs dry and a next page still exists.
Notice that all the fetching lives in hasNext(), and next() simply delegates to it. That gives us one place where state changes, and it makes repeated hasNext() calls harmless: once the buffer has elements, hasNext() returns true without any request. An ArrayDeque is used as the buffer because removeFirst() is constant time, unlike removing index 0 from an ArrayList.
3The Edge Cases That Usually Go Wrong
Fetching in the constructor is the first trap. It looks tidy, but it makes a network call even if the caller never iterates, for example when the iterator is created and then passed to code that decides to skip it. It also means that constructing the object can fail with a network error, which surprises callers. Keeping the first fetch in hasNext() makes the iterator fully lazy.
The second trap is the empty page with a token. Some APIs, especially ones that filter on the server or scan partitions, can return zero items and still give a next token. A simple if instead of the while loop in hasNext() would then report false and end the iteration early, silently losing every later page. The loop keeps fetching until it finds items or runs out of tokens. Notice that we also treat an empty string token as the end, because some APIs send "" instead of null; check what yours does.
The third question is error reporting. Iterator methods cannot throw checked exceptions, so an IOException must become an unchecked one. UncheckedIOException keeps the original as the cause, and the message includes the token, so a log tells us exactly which page failed. Whether to retry inside fetchPage() is a design decision: a small bounded retry for transient errors is reasonable, but endless retries hide outages, so many teams leave retries to the HTTP client's configuration. After a failure the iterator's state is unchanged, so a caller could call hasNext() again to retry the same page.
4Exposing It as a Stream
Streams are built on Spliterator, an iterator that can also describe itself and split for parallel work. The JDK can wrap any Iterator in a spliterator of unknown size, and StreamSupport turns that into a Stream.
The characteristics tell the stream framework what it can assume. ORDERED says the elements have a meaningful order, so operations such as limit keep the first elements. NONNULL says no element is null. We do not claim SIZED because we do not know the total in advance. The second argument false asks for a sequential stream. A parallel stream over this spliterator would only split by copying batches out of the iterator, which buys little for network-bound work and would make the thread-safety warning matter.
Laziness carries over: creating the stream makes no request, and limit(250) stops pulling after the 250th element, so the fourth page is never fetched. An alternative design is to implement Spliterator directly and fetch a page inside tryAdvance, which avoids the iterator but gives the same behaviour.
5Thread Safety and Resources
The iterator has mutable state, the buffer and the token, with no synchronisation, so two threads calling next() at once could take the same customer or corrupt the deque. That is normal for iterators, and the right response is to document it, as the Javadoc comment does, rather than add locks. If several workers need to process customers in parallel, one thread should iterate and hand customers to a pool.
Because the iterator holds no open connection between pages, it needs no close(). If the client kept a streaming connection open, we would make the stream closeable with onClose and ask callers to use try-with-resources.
6Follow-up questions
Why not fetch all pages into a List first?
For a few hundred customers that is fine and simpler. For a million customers it would hold every one in memory and make the caller wait for the last page before processing the first. The iterator holds at most one page, 100 customers, and lets processing start after the first request.
How would you test this iterator?
With a fake CustomerClient that returns scripted pages and counts calls. Useful cases are an empty result, exactly one page, a page of 100 followed by a page of 50, an empty page with a token followed by a page with items, calling hasNext() twice in a row, calling next() without hasNext(), next() after the end throwing NoSuchElementException, and an IOException surfacing as UncheckedIOException with the token in the message. The call counter proves laziness.
What if the data changes while we page through it?
Then the result depends on the API. Token-based paging usually continues from a position, so customers inserted behind the cursor are missed and deleted ones vanish; offset-based paging can skip or repeat items. The iterator cannot fix this; we either accept an approximately consistent scan or use an API that offers a snapshot or a change feed.
7Conclusion
In this answer, we built a lazy paging iterator over a REST API. It keeps a buffer of the current page and the next token, fetches inside hasNext() only when the buffer is empty and more pages exist, loops past empty pages, and lets next() take from the buffer or throw NoSuchElementException. It does no work in the constructor, turns IOException into an UncheckedIOException with the token as context, and is documented as not thread-safe. Wrapping it with Spliterators.spliteratorUnknownSize and StreamSupport.stream gives a lazy sequential Stream in which limit stops further requests.
Open with
I would keep three pieces of state: a deque buffering the current page, the next-page token, and a flag saying whether I have made the first call yet, because a null token means start before the first call and end after it.
Then, if they want more
All the fetching goes in hasNext: while the buffer is empty and there are more pages, fetch a page of 100, add the customers and store the new token.
It is a while loop, not an if, because an API can return an empty page that still has a next token. next calls hasNext and throws NoSuchElementException when it is false, otherwise takes the first element from the buffer.
I do not fetch in the constructor, so creating the iterator costs nothing if nobody iterates, and the network error does not happen at construction. Since Iterator cannot throw checked exceptions, I wrap IOException in UncheckedIOException with the page token in the message, so logs show which page failed. The class is not thread-safe and I document that.
To expose it as a stream I use StreamSupport.stream with Spliterators.spliteratorUnknownSize, passing ORDERED and NONNULL, and false for sequential. It stays lazy, so limit 250 makes only three requests.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
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 an Iterator<Customer> over a REST API that returns customers in pages of 100 with...": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/fb037cfa80/