Video in progress
What is mapMulti() and when is it more convenient than flatMap()?
mapMulti (Java 16+) lets you emit zero, one or several results from each element, but it doesn't create a new stream for each element: you accept the result into a Consumer. When an element yields few results, or the result type depends on a condition, it's lighter than flatMap.
📖 Answer
With flatMap, a Stream object is created for every element. If most elements yield zero or one result, that's unnecessary work.
// take only events of type Payment and cast them to that type
List<Payment> payments = events.stream()
.<Payment>mapMulti((e, sink) -> {
if (e instanceof Payment p) sink.accept(p);
})
.toList();
With flatMap you would have to write e instanceof Payment p ? Stream.of(p) : Stream.empty() for this.
It also works for unwrapping a nested structure:
orders.stream()
.<String>mapMulti((o, sink) -> o.items().forEach(sink))
.toList();
One thing: you often have to write the type argument (<Payment>) by hand, because the compiler can't infer it from the lambda. That makes it a bit harder to read.
I keep flatMap as the default and reach for mapMulti in two cases: when an element usually yields 0–1 results, or when imperative code (a loop, a condition) is more convenient for producing the result. There are primitive variants such as mapMultiToInt too.
Sign up to mark studied questions and save your progress.