Course contentsShow
← Java
Lesson 1436 of 2,87032. Streams API: Intermediate OperationsFree lesson

What flatMap Does: Flattening Nested Structures

Understanding how flatMap transforms each element into a stream and flattens the result into a single stream.

What flatMap Does: Flattening Nested Structures

You'll learn how flatMap transforms nested structures into a single, flat stream of elements.

The Problem: Streams of Streams

When you use map on elements that themselves produce streams, you end up with a nested structure: Stream<Stream<T>>. This is difficult to work with because you have streams inside streams, like boxes within boxes.

How flatMap Solves This

flatMap performs two operations in one:

  1. Transforms each element into a stream (using a function you provide)
  2. Flattens all those individual streams into a single stream

Think of it like this: if you have several bags of marbles and you use map, you'd get a collection of bags. With flatMap, you dump all the bags into one container, giving you just the marbles.

The Transformation Process

flatMap takes a Function<T, Stream<R>> — a function that converts each element into a stream. Instead of returning Stream<Stream<R>>, it automatically flattens the result into Stream<R>.

Example scenario: If each Person has a list of phone numbers, and you want all phone numbers from all people:

  • map(person -> person.getPhones().stream()) gives you Stream<Stream<String>>
  • flatMap(person -> person.getPhones().stream()) gives you Stream<String>

The "flat" in flatMap means it removes one level of nesting, producing a single continuous stream of elements.

Key Takeaway: flatMap transforms each element into a stream and automatically flattens all those streams into one, eliminating nested stream structures.