Stream.mapMulti()
Emit zero or more elements per input without creating intermediate streams.
Code Comparison
✕ Java 8
stream.flatMap(order ->
order.items().stream()
.map(item -> new OrderItem(
order.id(), item)
)
);
✓ Java 16+
stream.<OrderItem>mapMulti(
(order, downstream) -> {
for (var item : order.items())
downstream.accept(
new OrderItem(order.id(), item));
}
);
Why the modern way wins
Less allocation
No intermediate Stream created per element.
Imperative style
Use loops and conditionals directly.
Flexible
Emit zero, one, or many elements with full control.
Old Approach
flatMap + List
Modern Approach
mapMulti()
Since JDK
16
Difficulty
intermediate
JDK Support
Stream.mapMulti()
Available
Widely available since JDK 16 (March 2021)
How it works
mapMulti() is an imperative alternative to flatMap that avoids creating intermediate Stream objects for each element. It's more efficient when the mapping produces a small number of elements.