Quick revision
The short answer
Iterator's split hasNext and next force implementations to buffer one element and keep state between calls, and it has no way to describe its data or to be closed. Spliterator's single tryAdvance removes the buffering problem, its characteristics such as SIZED, ORDERED and IMMUTABLE let consumers optimise and split for parallelism, and BaseStream being AutoCloseable lets resource-backed sequences such as Files.lines be released. The lesson for new long-lived APIs is to model resource ownership, single use and data characteristics from the start.
What to remember
In this answer, we saw that Iterator's separate hasNext and next force read-ahead buffering and an easy-to-break protocol, which Spliterator's single tryAdvance removes. Spliterator characteristics such as SIZED, ORDERED and IMMUTABLE give consumers facts to optimise with, including splitting for parallelism. BaseStream being AutoCloseable lets resource-backed sequences such as Files.lines be released, and streams make single use explicit. For new long-lived APIs, we should design resource ownership, single use, characteristics and the advance operation into the types from the start, because none of them can be added cleanly later.
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.
Iterator's split hasNext and next force implementations to buffer one element and keep state between calls, and it has no way to describe its data or to be closed. Spliterator's single tryAdvance removes the buffering problem, its characteristics such as SIZED, ORDERED and IMMUTABLE let consumers optimise and split for parallelism, and BaseStream being AutoCloseable lets resource-backed sequences such as Files.lines be released. The lesson for new long-lived APIs is to model resource ownership, single use and data characteristics from the start.
Why this question is asked
Iteration interfaces outlive almost everything else in a codebase. Once dozens of services consume an iteration API, its shape decides what bugs they can write. The JDK has three generations of iteration interfaces, and each one fixes a weakness of the previous one, which makes them a free case study for anyone designing an API over remote or resource-backed data. Interviewers ask this question at a principal level to see whether we can draw design principles from concrete APIs. In this answer, we will look at the cost of hasNext and next as separate calls, at what Spliterator characteristics allow, at why Iterator cannot express resources, at single-use semantics, and finally at the principles for a new API.
1The Cost of Separate hasNext and next
Iterator asks two questions per element: is there another one, and give it to me. For an in-memory array, answering hasNext() is trivial. For a source where the only way to know whether another element exists is to try to read it, such as a socket, a parser or a database cursor, hasNext() must actually read the next element and park it in a field until next() asks for it. So every such iterator carries a one-element buffer and a small state machine.
| Interface | Advance | Describes its data | Can be closed |
|---|---|---|---|
| Iterator (1.2) | hasNext() then next() | No | No |
| Spliterator (8) | tryAdvance(action) | characteristics(), estimateSize() | No |
Stream / BaseStream (8) | internal, by the library | via its Spliterator | Yes, AutoCloseable |
Getting this right is where bugs live: a hasNext() that is not idempotent and reads a line on every call silently skips data when called twice. And callers must call the pair in the right order. Spliterator.tryAdvance(Consumer) merges both into one call: if an element exists, pass it to the action and return true; otherwise return false. No read-ahead, no buffer, no protocol between two methods.
2What Characteristics Let Consumers Do
A Spliterator reports characteristics as bit flags: ORDERED means elements have a defined order, SIZED means estimateSize() is exact, SUBSIZED means its splits are also exact, DISTINCT, SORTED and NONNULL describe the values, IMMUTABLE means the source cannot change, and CONCURRENT means it can change safely during traversal. These are promises the consumer can act on.
The stream library uses them constantly. If a source is SIZED, toArray() can allocate the exact array once instead of growing a buffer, and count() can, in some cases, skip traversal entirely. If it is SORTED, sorted() can be a no-op. If it is not ORDERED, a parallel stream can skip the work of preserving order. And trySplit() lets a parallel stream divide an ArrayList's range into halves recursively for fork/join workers, which is how parallelism works at all. An Iterator gives the consumer none of this: it knows nothing about its data, so the consumer must assume the worst.
3Resources That Iterator Cannot Release
Files.lines(path) returns a lazy Stream of the file's lines, holding an open file handle. If it returned an Iterator, a caller that stopped early would leak the handle with no way to release it. Because BaseStream extends AutoCloseable, the correct use is visible in the code and checked by tools.
Notice that most streams do not need closing: one built from a collection holds no resource, and close() does nothing. The type allows closing without requiring it, and the documentation of the method returning the stream says when it matters. The JDK also shows a middle path in DirectoryStream, which is Iterable and Closeable at once and allows iterator() to be called only once.
4Making Single Use Explicit
Iterable implies that we can call iterator() again and get a fresh pass. For a collection that is true. For a network response or a consumed file it is false, and an Iterable over such a source either re-fetches silently or fails in surprising ways. Streams state the rule outright: a stream can be consumed once, and a second terminal operation throws IllegalStateException with the message that the stream has already been operated upon or closed.
An explicit failure on misuse is far better than a quiet re-read that doubles the load on a remote service or returns different data the second time.
5Principles for a New Long-Lived API
Pulling this together, a new iteration API over remote or resource-backed data should answer four questions in its types, not only in its documentation. Who owns the resource and closes it: the API returns an AutoCloseable type and the caller closes it. Can it be consumed twice: if not, a second use fails fast. What does the consumer know about the data: order, exact size if known, whether it can change during traversal. And how does the consumer advance: through a single operation such as tryAdvance or a page-at-a-time call, rather than a two-call protocol that forces buffering.
The reason to decide this at the start is that each of these is hard to add later. Adding close() to a type that callers already use without try-with-resources does not make existing callers close it, and declaring single use after callers have learned to iterate twice breaks them. The JDK itself could not retrofit Iterator; it had to add new interfaces beside it.
- Ownershipreturns
AutoCloseable; the caller closes in try-with-resources - Use countsingle use, a second pass fails fast
- Characteristicsordered, sized, snapshot or live
- Advanceone call per element or per page, no read-ahead protocol
4 layers, from the top down. Step through them one at a time.
6Follow-up questions
Can we turn an existing Iterator into a Stream with characteristics?
Yes, with Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED | Spliterator.NONNULL) passed to StreamSupport.stream(spliterator, false), and then onClose to attach cleanup. If we know the exact size, Spliterators.spliterator(iterator, size, flags) reports SIZED. The flags must be true, because the stream library trusts them.
Is forEachRemaining on Iterator the same as tryAdvance?
It moves in the same direction. Since Java 8, Iterator.forEachRemaining(action) lets the iterator drive a loop internally, so a well-written implementation can avoid the per-element hasNext and next protocol. But it still gives no way to stop early except by throwing, and no characteristics or close.
Should every new API return a Stream?
Not necessarily. A Stream is a good default for a lazy, single-use, closeable sequence inside one process. For a paged remote API, a page-at-a-time method that returns records plus a continuation token is often clearer and works across process boundaries. The principles matter more than the type.
7Conclusion
In this answer, we saw that Iterator's separate hasNext and next force read-ahead buffering and an easy-to-break protocol, which Spliterator's single tryAdvance removes. Spliterator characteristics such as SIZED, ORDERED and IMMUTABLE give consumers facts to optimise with, including splitting for parallelism. BaseStream being AutoCloseable lets resource-backed sequences such as Files.lines be released, and streams make single use explicit. For new long-lived APIs, we should design resource ownership, single use, characteristics and the advance operation into the types from the start, because none of them can be added cleanly later.
Open with
I see three lessons. First, the advance protocol. Iterator splits hasNext and next, so any source where you only know there's another element by reading it, like a cursor or a parser, has to read ahead into a buffer and keep state between calls, and if hasNext isn't idempotent you silently lose elements.
Then, if they want more
Spliterator's tryAdvance does both in one call, so there's no buffer and no protocol to get wrong. Second, describing the data.
Spliterator reports characteristics such as ORDERED, SIZED, SUBSIZED, SORTED, NONNULL and IMMUTABLE, and consumers optimise with them: the stream library allocates exact arrays for sized sources, skips sorts on sorted ones, and uses trySplit to split work for parallel execution. An Iterator tells the consumer nothing, so it has to assume the worst. Third, resources and single use.
Iterator has no close, so Files.lines returning an iterator would leak file handles on early exit; BaseStream is AutoCloseable, so try-with-resources makes cleanup explicit. Streams also make single use explicit, failing with IllegalStateException on reuse instead of silently re-reading a source.
For a new API over remote data, I'd design those in from day one: return a closeable type the caller owns, make it single use and fail fast on reuse, document or report ordering, size and whether it's a snapshot or a live view, and use a single advance or page-at-a-time operation.
None of those can be retrofitted cleanly, which is why the JDK added new interfaces rather than fixing Iterator.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8
- 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
- The Collections Framework, overview, java.util, 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 "Iterator has no close method and separate hasNext and next calls, while Spliterator uses...": https://scrivio-interview-library.netlify.app/java/iteration/8d1799f878/