CKTIS / Java
Stream.mapMulti: practical reference
Stream.mapMulti: practical reference: mapMulti is a one-to-zero-or-many intermediate operation whose mapper sends each result to a supplied Consumer instead of creating a separate stream.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Stream.mapMulti(...)mapMulti is a one-to-zero-or-many intermediate operation whose mapper sends each result to a supplied Consumer instead of creating a separate stream.
Use it for a small number of outputs per input or imperative expansion to avoid constructing the child streams required by flatMap.
The Consumer supplied to the mapper may be used only during that mapper call; retaining it and invoking it later has undefined results.
The mapper may call the Consumer zero times; type inference sometimes needs an explicit , and call order determines result order for an ordered source.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var result = java.util.stream.Stream.of(1, 3).<Integer>mapMulti((n, out) -> { for (int i = 0; i < n; i++) out.accept(n); }).toList();
System.out.println(result);
}
}
Result
[1, 3, 3, 3]
The example exercises the documented element in a small deterministic program and compares exact standard output.