Java Reference ยท Streams and Functional
Java Stream.flatMap() method
Reference for Java Stream.flatMap(): turn each element into a stream and merge the results, flatten nested lists and optionals, and use the primitive variants.
flatMap() maps each element to a stream and then concatenates all those streams into one. Where map() gives exactly one output per input, flatMap() gives any number: zero, one or many. It is the standard way to flatten nested collections.
Each stream returned by the mapper is closed after its contents have been placed into the result. A null returned from the mapper is treated as an empty stream.
List<String> all = lists.stream() .flatMap(List::stream) .toList();
Try it
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.
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
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper) IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper) LongStream flatMapToLong(...) DoubleStream flatMapToDouble(...)
| Name | Description |
|---|---|
mapper |
Returns a stream of replacement elements for each input element. Must be stateless and non-interfering. |
Returns: a stream of all replacement elements, grouped in input order.
Usage notes
- Zero, one or many: returning
Stream.empty()drops the element, soflatMapcan filter and map in one step, thoughfilterplusmapis usually clearer. - Flatten one level only. Deeper nesting needs a nested
flatMapor recursion. - Optional:
flatMap(Optional::stream)is the idiom for discarding empty optionals; on anOptionalitself,Optional.flatMapavoidsOptional<Optional<T>>. - Laziness: historically
flatMapconsumed the whole inner stream before short-circuiting. Since Java 10 the inner streams are consumed lazily, sofindFirst()orlimit()over infinite inner streams works. - Allocation: each element creates a small stream; for very hot paths
mapMulti()can be cheaper when results per element are few. - Primitive streams:
IntStream.flatMaptakes a function returningIntStream, with no boxing. - Checked exceptions in the mapper have to be wrapped, as in
map.
Related
map(),mapMulti(),distinct()andsorted(),Optional- Lessons: Advanced streams, Streams