Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Stream.flatMap()

Turns each element into a stream and joins all streams into one.

Available since: Java 8

Syntax

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)

Parameters

ParameterTypeDescription
mapperFunction<? super T, ? extends Stream<? extends R>>A function that turns an element into a stream.

Return value

Stream<R>One combined stream of all produced streams.

Examples

A list of lists into one list:

void main() {
    List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3), List.of(4, 5));
    List<Integer> flat = nested.stream().flatMap(List::stream).toList();
    IO.println(flat);
}

Output:

[1, 2, 3, 4, 5]

All unique words from lines:

void main() {
    List<String> lines = List.of("to be", "or not", "to be");
    List<String> words = lines.stream()
        .flatMap(line -> Arrays.stream(line.split(" ")))
        .distinct()
        .toList();
    IO.println(words);
}

Output:

[to, be, or, not]

Notes

map() would give a stream of collections (Stream<List<Integer>>), while flatMap() unpacks them into a stream of elements. The function must return a Stream, so for lists write List::stream and for arrays Arrays::stream.

See also

Related recipes

In the tutorial

  • Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.

Thanks for reading!

Donate to the site — we work hard for you.