Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

Before JDK 10, flatMap was not lazy: Stream.of(1).flatMap(i -> Stream.iterate(0, x -> x + 1)).findFirst() never finished. Explain why and when mapMulti may be preferable to flatMap.

Before JDK 10, flatMap took each inner stream and pushed every one of its elements downstream with forEach, without ever asking whether the rest of the pipeline still wanted more. An infinite inner stream therefore never ended, even under findFirst. JDK 10 changed flatMap to check for cancellation between inner elements, and Java 16 added mapMulti, which is often the better choice when each element produces only a few results or when deciding the results takes ordinary imperative code.

Why this question is asked

flatMap is one of the operations we reach for constantly: orders to order lines, files to words, users to roles. Most of the time we never think about how it hands those inner elements on. Interviewers ask about the old bug because it tests whether we understand how a pipeline moves elements and how short-circuiting stops it, and mapMulti shows whether we know the cost of a small stream per element. In this answer, we will recap how elements flow through a pipeline, reproduce the old problem, look at what JDK 10 changed inside flatMap, and then see when mapMulti is preferable and when flatMap stays the clearer choice.

1A Quick Recap of How a Stream Pulls Elements

A stream pipeline does nothing until a terminal operation such as findFirst, toList or count starts it. Then the source hands elements, one at a time, to a chain of small objects called sinks, one sink per stage. Each sink does its job (filtering, mapping) and passes the result to the next sink, which is called the downstream.

Some terminal operations do not need every element. findFirst, anyMatch and limit are called short-circuiting operations: as soon as they have their answer, they want the source to stop. They signal this through a method on the sink called cancellationRequested(). The source loop checks it before pushing each element, and stops as soon as it returns true.

flatMap is special because one input element turns into a whole stream of outputs, the inner stream. So flatMap has its own little loop inside it, the loop that moves the inner stream's elements to the downstream. Whether that inner loop also checks cancellationRequested() is the whole story of this question.

2Reproducing the Problem

Here is the pipeline from the question. The outer stream has a single element, and flatMap maps it to an infinite stream that counts 0, 1, 2 and so on.

Java
Optional<Integer> first = Stream.of(1)
.flatMap(i -> Stream.iterate(0, x -> x + 1))
.findFirst();
System.out.println(first);
// JDK 8 and 9: never prints, the thread spins forever (CPU at 100%)
// JDK 10 and later: Optional[0]

Notice that findFirst only needs one element, and the very first inner element, 0, is enough. On JDK 8 the program still never finishes. The outer source dutifully checks for cancellation before pushing its single element, but by then the damage is done: the one element is enough to start an endless inner loop.

3Why the Old flatMap Never Stopped

In JDK 8 and 9, the sink that flatMap installed looked roughly like this. For each outer element it called the mapper, got the inner stream, and handed that stream's elements to the downstream with forEach.

Java
// simplified from the JDK 8 flatMap sink
public void accept(T u) {
try (Stream<? extends R> result = mapper.apply(u)) {
if (result != null)
result.sequential().forEach(downstream); // pushes every inner element
}
}
Step throughfindFirst asks to stop, the old flatMap does not listen
Outer sourceflatMap sinkInner streamfindFirst
accept(1)
mapper.apply(1), then forEach(downstream)
push 0: answer found
cancellationRequested() is now true
push 1, 2, 3 ... ignored, forever

5 messages in order. Play them, or step through them one at a time.

The outer loop checks for cancellation; the inner forEach in JDK 8 and 9 never does.

forEach has no way to stop part-way. It pushes the first inner element, 0, and findFirst stores it and starts saying "cancel" from then on. But forEach never asks. It keeps pushing 1, 2, 3 forever, and findFirst quietly ignores each one. With a finite inner stream this only wastes work. With an infinite inner stream, or a huge one such as all lines of a large file, it hangs or reads everything.

So the stream was lazy from the outside, between outer elements, but eager on the inside, within each inner stream.

4What JDK 10 Changed

JDK 10 fixed this. The flatMap sink now remembers whether the downstream is a short-circuiting one, which it can tell because the pipeline calls its cancellationRequested() method. If it is, flatMap no longer uses forEach. It takes the inner stream's spliterator and advances it one element at a time, checking for cancellation before each step.

Java
// simplified from the JDK 10+ flatMap sink
if (!cancellationRequestedCalled) {
result.sequential().forEach(downstream); // nobody can cancel: fast path
} else {
Spliterator<? extends R> s = result.sequential().spliterator();
do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstream));
}

Notice that the fast path is kept for pipelines that can never be cancelled, such as toList, where pushing everything is exactly what we want. Only short-circuiting pipelines pay for the per-element check. Since then, findFirst, anyMatch, limit and takeWhile stop consuming the inner stream as soon as they have their answer, so the example prints Optional[0] on Java 10 and later.

5What mapMulti Is and Why It Can Be Cheaper

Java 16 added mapMulti. Instead of returning a stream for each element, our function receives the element and a consumer, often called the sink, and calls sink.accept(x) once for each output it wants to produce. Zero calls means no output.

Java
// flatMap: a new Stream object for every input element
List<Integer> a = Stream.of(1, 2, 3)
.flatMap(n -> n % 2 == 1 ? Stream.of(n, -n) : Stream.empty())
.toList(); // [1, -1, 3, -3]
// mapMulti: no inner stream at all, we push the outputs ourselves
List<Integer> b = Stream.of(1, 2, 3)
.<Integer>mapMulti((n, sink) -> {
if (n % 2 == 1) { sink.accept(n); sink.accept(-n); }
})
.toList(); // [1, -1, 3, -3]

Both give the same result, but flatMap builds a Stream object, with its pipeline and spliterator, for every input element just to deliver two numbers or none. Over millions of elements those short-lived objects add allocation and garbage collection work. mapMulti creates nothing per element; it passes the values straight on.

The second reason to prefer mapMulti is clarity when choosing the outputs needs real logic. Inside the lambda we can write if statements, loops and early returns, as in the example below, instead of bending that logic into nested ternaries that each return a different stream. One small catch: Java often cannot infer the output type, so we write the type witness, as in .<Integer>mapMulti or .<Line>mapMulti.

6Choosing Between mapMulti and flatMap

Here is a more realistic case, where an order contributes its positive-quantity lines, unless it was cancelled.

Java
record Line(String sku, int qty) {}
record Order(String id, boolean cancelled, List<Line> lines) {}
Stream<Line> lines = orders.stream().<Line>mapMulti((order, sink) -> {
if (order.cancelled()) return; // emits nothing for this order
for (Line l : order.lines()) {
if (l.qty() > 0) sink.accept(l); // emits only the lines we want
}
});
// When the inner elements already are a collection, flatMap reads better:
Stream<Line> all = orders.stream().flatMap(o -> o.lines().stream());
flatMap or mapMulti
SituationBetter choiceWhy
Inner elements already in a List or StreamflatMapo.lines().stream() says it all
Zero, one or two outputs per elementmapMultino Stream object per element
Outputs decided by if/loop logicmapMultiplain imperative code in the lambda
Inner source is huge or infiniteflatMap (JDK 10+)it can stop part-way; mapMulti cannot
Numeric outputsmapMultiToInt and friendsavoids boxing as well
Both produce the same elements; they differ in cost and in how the code reads.

So the rule of thumb is simple. When each element already holds its results as a collection or a stream, flatMap with o.lines().stream() is shorter and says exactly what it does. When each element maps to a handful of results, or deciding them needs branches and loops, mapMulti is cheaper and often easier to read.

7Follow-up questions

Does mapMulti also stop early under findFirst?

Not in the middle of one element. The lambda calls sink.accept as many times as it wants, and there is no way for the downstream to tell it to stop until the lambda returns. The stream ignores the extra elements, but the lambda still runs to the end. That is fine for a few outputs per element, and it is exactly why an infinite or very large inner source should stay with flatMap, which since JDK 10 can stop part-way through the inner stream.

Why not always use mapMulti for speed?

Because the difference only matters when the per-element Stream allocation is a real share of the work, which is rare outside tight loops over many elements. For ordinary business code the readability of flatMap(o -> o.lines().stream()) is worth more, and a profiler or JMH benchmark should show the allocation before we trade clarity for it.

8Conclusion

In this answer, we saw that before JDK 10 the flatMap sink pushed each inner stream to the downstream with forEach, which never checks cancellationRequested(), so an infinite inner stream ran forever even under findFirst. JDK 10 made flatMap advance the inner spliterator one element at a time when the pipeline can short-circuit. We also saw that Java 16's mapMulti avoids building a Stream for every element and lets us decide the outputs with plain imperative code, while flatMap remains the clearer and safer choice when the inner elements already come as a collection or stream, especially a large or infinite one.

What to say in the interviewAbout 80 seconds aloud

Open with

In JDK 8 and 9, flatMap's sink took the inner stream and called forEach(downstream) on it. Short-circuiting operations like findFirst stop the pipeline by making cancellationRequested return true, and the outer source checks that, but forEach inside flatMap never did.

Then, if they want more

So Stream.of(1).flatMap(i -> Stream.iterate(0, x -> x + 1)).findFirst() found 0 and then kept receiving 1, 2, 3 forever. JDK 10 fixed it: when the downstream can cancel, flatMap pulls the inner spliterator with tryAdvance and checks cancellation before each element, so on modern Java it returns Optional of 0 straight away.

As for mapMulti, added in Java 16, instead of returning a stream per element we get a consumer and call accept for each output.

That avoids allocating a Stream pipeline per element, which matters in hot paths where each element produces zero, one or two results, and it lets me write the selection logic with ifs and loops instead of nested ternaries returning Stream.empty(). I usually need a type witness, like .<Line>mapMulti.

But when the element already has a collection, flatMap with lines().stream() is clearer, and for a very large or infinite inner source I keep flatMap, because mapMulti cannot stop in the middle of one element.

About this answer

Last updated
12 November 2026
Versions it names
Java 10, Java 8, Java 16
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 "Before JDK 10, flatMap was not lazy: Stream.of(1).flatMap(i -> Stream.iterate(0, x -> x...": https://scrivio-interview-library.netlify.app/java/streams/3691e955e5/