Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Streams and Functional

Java Stream.mapMulti() method

Reference for Java 16 Stream.mapMulti(): emit zero, one or many output elements per input with a consumer, and when it beats flatMap().

mapMulti() (Java 16) is an intermediate operation like flatMap(): each input element can produce zero, one or many output elements. Instead of returning a stream, your function receives the element and a Consumer called the sink; you call sink.accept(x) once for every output you want.

It avoids creating a small temporary stream per element, so it is a good fit when most inputs produce few outputs, or when the logic is easier to write imperatively than as a stream expression.

Java
Stream.of(1, 2, 3).<Integer>mapMulti((n, sink) -> {
    sink.accept(n);
    sink.accept(n * 10);
});

Try it

Java Zero, one or many outputs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Filtering by type and the same with flatMap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
<R> Stream<R> mapMulti(BiConsumer<? super T, ? super Consumer<R>> mapper)
IntStream mapMultiToInt(BiConsumer<? super T, ? super IntConsumer> mapper)
LongStream mapMultiToLong(...)
DoubleStream mapMultiToDouble(...)
Name Description
mapper Called once per element with the element and a sink consumer. Call sink.accept(...) for every output.

Returns: a new stream of the emitted elements.

Usage notes

  • Explicit type witness: Java often cannot infer R from a lambda body that only calls sink.accept. Write .<String>mapMulti(...) as in the examples.
  • Order: outputs for one input stay in the order you emit them, and inputs keep their encounter order.
  • When to prefer it: small or conditional expansions, and cases where creating a stream per element is wasteful. For ordinary one-to-many expansion with an existing collection, flatMap() is shorter.
  • Do not keep the sink: use the consumer only inside the call. Storing it or calling it from another thread is not supported.
  • Laziness: like map(), it runs only when a terminal operation pulls elements.
  • Version: Java 16 and later.