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

flatMap Signature and Lambda Requirements

Examining the flatMap method signature and why it requires a function returning Stream<T>.

flatMap Signature and Lambda Requirements

You'll learn: Why flatMap demands a function that returns a Stream, and what that means for the lambdas you write.

Understanding the Method Signature

The flatMap operation has a specific signature:

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

Let's break this down in plain English: flatMap accepts a function that takes each element of type T and must return a Stream<R>—not just a single value like map does.

Why It Requires Stream-Returning Functions

Remember that flatMap solves the problem of nested structures (like lists of lists). To flatten them, it needs each input element to be expanded into multiple output elements. A Stream is the perfect container for "zero or more elements."

Think of it like this: if you have a box of boxes, flatMap opens each inner box and spreads its contents into one big pile. To do that, your function must tell flatMap what's inside each inner box—and that "inside view" is expressed as a Stream.

Lambda Requirements

Your lambda or method reference passed to flatMap must produce a Stream:

// Correct: returns Stream<String>
list.flatMap(sentence -> Stream.of(sentence.split(" ")))

// Correct: method reference returning Stream
list.flatMap(Collection::stream)

// WRONG: returns String[], not Stream
// list.flatMap(sentence -> sentence.split(" "))

If you try to return a non-Stream type (like an array or single object), the compiler will reject it—the types won't match.

Key Takeaway: flatMap requires a function that returns Stream<R> because it needs to flatten multiple elements per input; your lambda must produce that stream of elements, not individual values.