Lesson · Stream API
Intermediate operations: filter, map, flatMap and the stateful ones
15 min readIntermediate Operations
Intermediate operations describe transformations without running them. Most are stateless and look at one element at a time; a few are stateful and must see everything before emitting anything, and that difference changes how pipelines behave.
Lazy by contract
Every intermediate operation returns a new stream, which is what makes chaining possible. None of them executes when you write it; they append a stage to the pipeline and hand the stream back. Only the terminal operation at the end starts pulling elements through all stages.
This is not an optimization detail, it is the design: it lets limit stop upstream stages early, lets findFirst touch only the elements it needs, and keeps the whole pipeline allocation-free until asked.
stream.filter(rule).map(fn).sorted().limit(3) // builds a pipeline: zero elements processed .collect(Collectors.toList()); // runs the pipeline: the only line that does work
The catalog that matters
The operations below cover nearly everything you will meet. The stateful column is the one to internalize: stateful operations must see the entire stream before they can emit anything.
| Operation | Does | Stateful? |
|---|---|---|
| filter(p) | keeps elements that pass the predicate | no |
| map(f) | transforms each element 1-to-1 | no |
| flatMap(f) | maps each element to a stream, then concatenates | no |
| peek(consumer) | side effect per element, for debugging | no |
| distinct() | removes duplicates via equals/hashCode | yes |
| sorted() | orders all elements before emitting any | yes |
| limit(n) / skip(n) | cuts the stream short / drops a prefix | cheap, order-aware |
| takeWhile(p) / dropWhile(p) | runs until the predicate first fails / after it | cheap, order-aware |
Why stateful operations change the rules
sorted and distinct cannot emit their first element until they have seen the last one. For a finite list that is fine. For an infinite generator it means the pipeline never produces anything: Stream.iterate(...).sorted() hangs, because sorted is still waiting for more input, and limit(3) after it never gets to count.
The mirror case is fine: Stream.iterate(...).limit(3).sorted() works, because limit cuts the infinite stream down before sorted receives it. Where a bounding operation appears decides whether the pipeline can terminate.
Stream.iterate(1, n -> n + 1).sorted().limit(3); // never completes: sorted waits for all input Stream.iterate(1, n -> n + 1).limit(3).sorted(); // fine: limit bounds the stream first
Order matters, and it is a semantic choice
Because each operation transforms the stream the next one sees, swapping two operations can change the meaning entirely. Compare limit before sorted (sort the first two) with sorted before limit (take the two smallest of all). Both compile; only one matches your intent.
Stream.of(9, 1, 8, 2).limit(2).sorted(); // first two: [9, 1] then sorted -> [1, 9] Stream.of(9, 1, 8, 2).sorted().limit(2); // all four sorted -> [1, 2]
Ops bench · same input, different position
two experiments5 fails the test, so the stream stops there: 6 and 8 are never even examined. Stops at the first failure.
output: [2,4]
source: [9, 1, 8, 2]
limit(2) keeps only [9, 1] before sorting is even involved, so sorting happens over two elements.
output: [1,9]
flatMap: one element in, a stream out
map is a strict one-to-one transformation: one element becomes one element. When each element should become zero, one, or many, flatMap is the tool: it maps each element to a stream and then concatenates the results into a single stream.
Typical uses: flatten a list of lists, split sentences into words, expand an optional-like step that produces nothing sometimes. Sentence splitting also shows why flatMap is map plus flattening: map(sentence -> sentence.split(" ")) would give you a stream of arrays, not words.
List<List<Integer>> groups = List.of(List.of(1, 2), List.of(3), List.of(4, 5)); groups.stream().flatMap(List::stream).collect(Collectors.toList()); // [1, 2, 3, 4, 5]
takeWhile vs filter, and what peek is for
filter tests every element, takeWhile stops at the first failure. Sorted input with a consistent rule makes them look identical, but the contract is completely different: takeWhile is ordered and short-circuits, filter never stops early.
peek exists for observing a pipeline while debugging. It is an intermediate operation, so it runs only when a terminal operation is present, and each element passes through it in source order. Using peek to mutate state in production is a classic trap for a later lesson; use it to look, not to act.
A stage's position is not decoration: bounding operations (limit, takeWhile) decide where infinite data becomes finite, and stateful operations decide where order and completeness are required.
Intermediate operations never run alone
Write a pipeline, forget the terminal, and absolutely nothing happens, no exceptions, no output, no work. If a pipeline seems to do nothing, the first thing to check is whether it ever ends in a terminal operation.
Interview angles
Which intermediate operations are stateful, and why does it matter?+
sorted and distinct are stateful: they buffer or track elements and can emit nothing until the stream ends. On infinite streams that means they never produce, and in parallel streams they impose coordination cost.
Difference between takeWhile and filter?+
filter tests every element; takeWhile consumes up to and stops at the first element that fails, so it is only sensible on ordered streams. With sorted input and a predicate that fails monotonically they agree; otherwise they diverge.
What does flatMap do that map cannot?+
flatMap maps each element to a stream of zero or more elements and concatenates the results, enabling one-to-many expansion (splitting words, flattening nested lists). map is strictly one-to-one.
When should you use peek?+
For debugging and nothing else. It observes elements as they pass; mutating shared state through peek (adding to a list, incrementing counters) breaks laziness assumptions and parallel streams, and belongs in a terminal or a collector instead.
Does limit before sorted behave the same as sorted before limit?+
No. limit(2).sorted() sorts only the first two elements, while sorted().limit(2) sorts everything and takes the two smallest. Position decides which elements are bounded when.