Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

How is a stream pipeline represented inside the JDK? Explain the role of stream flags such as SIZED, SORTED and DISTINCT and how they let operations be skipped.

Inside the JDK, each stream stage is a pipeline object linked to the stage before it, and the terminal operation turns the stages into a chain of Sinks that each push elements to the next. The source Spliterator reports characteristics such as SIZED, SORTED and DISTINCT, which become stream flags that every stage keeps, sets or clears. Operations read the flags to skip work: sorted() on an already SORTED stream and distinct() on a DISTINCT one do nothing, and since Java 9 count() on a SIZED stream returns the size without traversing. Stateful operations such as sorted act as barriers that buffer every element.

Why this question is asked

Most of the time we can use streams without knowing how they are built, but some behaviour only makes sense once we see the machinery: a peek that never prints, a sorted() that seems free, a filter that runs for every element even though findFirst is at the end. Interviewers ask this internals question at a mid-senior level to check that we have looked under the hood and can reason about performance from first principles. In this answer, we will recap the pieces involved, follow how stages become a chain of Sinks, see where the flags come from, watch the JDK use them to skip work, and finish with stateful operations as barriers.

1A Quick Recap of the Pieces

A Spliterator is the source's iterator for streams: it can hand out elements one by one with tryAdvance or all at once with forEachRemaining, split itself in two for parallel work, and report characteristics, which are bit flags describing the data, such as SIZED (it knows exactly how many elements it has), SORTED, DISTINCT, ORDERED and NONNULL.

A Sink is the JDK's internal consumer for one stage. Besides accept(element), it has begin(size), called before any element arrives with the size if known, end(), called after the last element, and cancellationRequested(), which lets a short-circuiting stage say it needs no more. These classes live in java.util.stream and are package-private, so we never use them directly, but they explain everything else.

2Stages as a Linked Pipeline

Calling list.stream() creates the head stage, an instance of ReferencePipeline.Head that holds the Spliterator. Each intermediate operation creates a new stage object, a StatelessOp for filter or map and a StatefulOp for sorted or distinct, which points back to its upstream stage and records its own operation flags. Nothing runs yet; we just have a linked list of stage descriptions.

When the terminal operation is called, it walks back along this list from the last stage to the first and asks each stage to wrap the sink after it. Each stage's opWrapSink returns a new Sink that does its job and passes results to the downstream sink. The result is a chain of Sinks in source order, ending in the terminal operation's own sink.

Java
// list.stream().filter(s -> s.length() > 1).map(String::toUpperCase).toList()
// Stages (built by the calls): Head -> filter(StatelessOp) -> map(StatelessOp)
// Sinks (built by toList, wrapped back to front):
// filterSink.accept(s) { if (s.length() > 1) mapSink.accept(s); }
// mapSink.accept(s) { listSink.accept(s.toUpperCase()); }
// Then, roughly:
// filterSink.begin(spliterator.getExactSizeIfKnown());
// spliterator.forEachRemaining(filterSink);
// filterSink.end();
Step throughSink chain built by the terminal operation
  1. Spliteratorsource; reports SIZED, ORDERED
  2. filter sinkpasses matching elements on
  3. map sinktransforms and passes on
  4. toList sinkcollects the results

4 layers, from the top down. Step through them one at a time.

Elements are pushed down the chain one at a time.

Notice that there is no list between stages. Each element goes into the first sink and is pushed through the whole chain before the next element is read. For short-circuiting terminals such as findFirst, the loop instead calls tryAdvance one element at a time and checks cancellationRequested() between them, which is how the pipeline stops early.

3Where the Stream Flags Come From

At the head stage, the Spliterator's characteristics are translated into stream flags. The relevant ones are DISTINCT, SORTED, ORDERED, SIZED and SHORT_CIRCUIT. Each operation then declares what it does to each flag: it may preserve it, set it or clear it. The pipeline computes the combined flags for every stage, so at any point the JDK knows what is guaranteed about the elements flowing there.

How sources and operations affect the flags
Source or operationSIZEDSORTEDDISTINCT
ArrayList.stream()set--
TreeSet.stream()setsetset
HashSet.stream()set-set
filterclearedkeptkept
mapkeptclearedcleared
sorted() natural orderkeptsetkept
distinct()clearedkeptset
A dash means the flag is not set. Some JDK versions keep SIZED through more operations; check your version.

The reasons are intuitive once we think about what each operation can change. filter may remove elements, so the exact size is no longer known. map can produce equal values from different inputs and destroy ordering, so DISTINCT and SORTED are gone, but it never changes how many elements there are, so SIZED survives. sorted() makes the stream SORTED by definition, and distinct() makes it DISTINCT.

4How Operations Use the Flags to Skip Work

When sorted() with natural ordering builds its sink and sees that the upstream flags already include SORTED, it simply returns the downstream sink unchanged: the stage exists but does nothing. distinct() does the same when the stream is already DISTINCT. So treeSet.stream().sorted().distinct() costs nothing extra. Note that sorted(comparator) with a custom comparator cannot use the shortcut, because SORTED only means natural order.

The most visible shortcut is count(). Since Java 9, if the stream is SIZED at the terminal, count() returns the size from the Spliterator without traversing anything.

Java
List<Integer> nums = List.of(3, 1, 2);
long a = nums.stream().peek(System.out::println).count();
// prints nothing, a = 3: SIZED, so the pipeline is never traversed (Java 9+)
long b = nums.stream().filter(n -> n > 1).peek(System.out::println).count();
// prints 3 and 2, b = 2: filter cleared SIZED, so count must traverse

Notice that peek is skipped in the first case. The flags let the JDK prove the answer without running the stages, and the specification of count() allows it. This is why side effects in peek or map are unreliable.

5Stateful Operations as Barriers

A stateless operation such as filter can handle each element on its own. A stateful operation such as sorted cannot: it cannot emit the smallest element until it has seen all of them. Its sink therefore collects every element into a buffer in accept, sorts the buffer in end(), and only then pushes the elements downstream, calling begin, accept and end on the next sink.

Java
Stream.of("c", "a", "b")
.peek(s -> System.out.println("before " + s))
.sorted()
.peek(s -> System.out.println("after " + s))
.findFirst();
// before c, before a, before b all elements reach the buffer first
// after a then findFirst stops after one

So a stateful operation splits the pipeline into two passes and holds all elements in memory between them. On a large or infinite stream, sorted will buffer everything, which is why sorted() on Stream.iterate never finishes even with findFirst after it. distinct is a partial barrier: it passes elements on immediately but must remember every element seen so far in a set.

6Follow-up questions

Why do these flags matter for parallel streams?

ORDERED tells the framework whether it must preserve encounter order when combining results, and SIZED and SUBSIZED let it split work into exact ranges and write results directly into a pre-sized array. Calling unordered() clears ORDERED and can make operations such as distinct or limit cheaper in parallel.

Can I see the flags of a stream?

Not directly through a public API on Stream, but stream.spliterator().characteristics() shows the characteristics of the stream at that point, which reflect the combined flags. It is a useful way to check whether a stage keeps SIZED, though calling it consumes the stream.

Why is count() allowed to skip side effects?

Because the documentation states that an implementation may choose not to execute the pipeline if it can compute the count directly from the source. Side effects in intermediate operations were never guaranteed to run for every element, so code that relied on them was already relying on unspecified behaviour.

7Conclusion

In this answer, we followed how the JDK represents a stream. Each operation adds a pipeline stage linked to its upstream, and the terminal operation wraps the stages back to front into a chain of Sinks that elements are pushed through one at a time. The source Spliterator's characteristics become stream flags that each stage keeps, sets or clears, and operations use them to skip work: sorted() and distinct() become no-ops on SORTED or DISTINCT streams, and count() on a SIZED stream returns the size without traversing since Java 9. Stateful operations such as sorted buffer every element and act as barriers.

What to say in the interviewAbout 90 seconds aloud

Open with

Inside the JDK, every stream operation creates a stage object, a Head for the source, then StatelessOp or StatefulOp for each intermediate operation, and each stage points back to its upstream.

Then, if they want more

Nothing runs until the terminal operation. The terminal walks back from the last stage and asks each one to wrap the sink after it, so we get a chain of Sinks in source order, each with begin, accept, end and cancellationRequested.

Then it calls begin with the size if known, pushes elements from the Spliterator through the chain one at a time, and calls end. Short-circuiting terminals use tryAdvance and check cancellationRequested between elements.

The flags come from the Spliterator's characteristics, like SIZED, SORTED, DISTINCT and ORDERED, and each operation preserves, sets or clears them: filter clears SIZED, map keeps SIZED but clears SORTED and DISTINCT, sorted sets SORTED.

Operations use them to skip work: sorted with natural order on a stream that's already SORTED just returns the downstream sink, distinct does the same on a DISTINCT stream, and since Java 9 count on a SIZED stream returns the size without traversal, which is why a peek before count may never print.

Stateful operations like sorted are barriers: the sink buffers every element in accept, sorts in end, and only then pushes them downstream, so it holds everything in memory and never finishes on an infinite stream.

About this answer

Last updated
12 November 2026
Versions it names
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.
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 "How is a stream pipeline represented inside the JDK? Explain the role of stream flags...": https://scrivio-interview-library.netlify.app/java/streams/0ed17115fd/