Streams: mapMulti flattens without a Stream per element

Java 16's mapMulti pushes zero or more results into a consumer, avoiding the intermediate Stream that flatMap allocates for every element.

Code
record Order(String id, List<String> items) {}
var orders = List.of(new Order("A", List.of("pen", "book")),
                     new Order("B", List.of()),
                     new Order("C", List.of("mug")));

List<String> items = orders.stream()
        .<String>mapMulti((order, downstream) -> order.items().forEach(downstream))
        .toList();
System.out.println(items);
Output
[pen, book, mug]
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30