Stream.mapMulti()
Code Comparison
stream.flatMap(order ->
order.items().stream()
.map(item -> new OrderItem(
order.id(), item)
)
);
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()
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.
Related Documentation
Proof