CKTIS / Java
Stream.flatMap: practical reference
Stream.flatMap: practical reference: flatMap is a one-to-many intermediate operation that replaces each element with the contents of a mapper-produced stream and flattens those results.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Stream.flatMap(...)flatMap is a one-to-many intermediate operation that replaces each element with the contents of a mapper-produced stream and flattens those results.
Use it to expand nested collections, lines into words, or parent-child relations when each source element yields zero or many outputs.
The mapper must be stateless and non-interfering; every produced stream is closed after its contents are consumed, so it must not be reused later.
A null stream returned by the mapper is treated as empty; null elements inside a mapped stream can flow onward, and ordered sources retain encounter order.
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(java.util.List.of(1, 2), java.util.List.of(3)).flatMap(java.util.Collection::stream).toList();
System.out.println(result);
}
}
Result
[1, 2, 3]
The example exercises the documented element in a small deterministic program and compares exact standard output.