Skip to content
Tutorials Center
My learning

Topics

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.

Java
List<String> all = lists.stream()
    .flatMap(List::stream)
    .toList();

Try it

Java Flattening lists and splitting text

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 Pairs, optionals and primitives

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> 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, so flatMap can filter and map in one step, though filter plus map is usually clearer.
  • Flatten one level only. Deeper nesting needs a nested flatMap or recursion.
  • Optional: flatMap(Optional::stream) is the idiom for discarding empty optionals; on an Optional itself, Optional.flatMap avoids Optional<Optional<T>>.
  • Laziness: historically flatMap consumed the whole inner stream before short-circuiting. Since Java 10 the inner streams are consumed lazily, so findFirst() or limit() 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.flatMap takes a function returning IntStream, with no boxing.
  • Checked exceptions in the mapper have to be wrapped, as in map.