0Pricing
Java Academy · Lesson

flatMap for Nested Collections

Flatten nested lists, Optional chains, and file-line structures using flatMap.

The Nested Collection Problem

When each element of a stream maps to another collection, map gives you a Stream<List<T>>. flatMap merges the inner streams into one flat Stream<T>.

List<List<Integer>> nested = List.of(List.of(1,2), List.of(3,4), List.of(5));
// With map:
Stream<List<Integer>> s = nested.stream().map(l -> l); // Stream<List<Integer>>
// With flatMap:
Stream<Integer> flat = nested.stream().flatMap(List::stream); // Stream<Integer>
flat.forEach(System.out::println); // 1 2 3 4 5

flatMap vs map

map(f) applies f to each element and wraps the result. flatMap(f) applies f which returns a stream, then concatenates all those streams into one.

// map: List<String> -> Stream<Stream<Character>>
Stream<Stream<Character>> nested = List.of("hi","bye").stream()
    .map(s -> s.chars().mapToObj(c -> (char)c));
// flatMap: List<String> -> Stream<Character>
Stream<Character> flat = List.of("hi","bye").stream()
    .flatMap(s -> s.chars().mapToObj(c -> (char)c));

All lessons in this course

  1. flatMap for Nested Collections
  2. Parallel Streams: Performance and Pitfalls
  3. Spliterator: Splitting for Parallelism
  4. Infinite Streams with iterate and generate
← Back to Java Academy