0
0
JavaHow-ToBeginner · 3 min read

How to Use Stream flatMap in Java: Syntax and Examples

In Java, flatMap is used with streams to convert each element into a stream and then flatten all those streams into one. It helps when you have nested collections and want to process all elements in a single stream.
📐

Syntax

The flatMap method takes a function that maps each element of the original stream to a new Stream. It then flattens these streams into one continuous stream.

  • stream.flatMap(function): Applies the function to each element.
  • The function returns a Stream for each element.
  • The result is a single flattened Stream of all elements from those streams.
java
Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
💻

Example

This example shows how to use flatMap to flatten a list of lists of strings into a single stream of strings and print each one.

java
import java.util.*;
import java.util.stream.*;

public class FlatMapExample {
    public static void main(String[] args) {
        List<List<String>> listOfLists = Arrays.asList(
            Arrays.asList("apple", "banana"),
            Arrays.asList("cat", "dog"),
            Arrays.asList("egg", "fish")
        );

        List<String> flatList = listOfLists.stream()
            .flatMap(List::stream) // flatten each inner list to a stream
            .collect(Collectors.toList());

        flatList.forEach(System.out::println);
    }
}
Output
apple banana cat dog egg fish
⚠️

Common Pitfalls

Common mistakes when using flatMap include:

  • Returning a collection or array instead of a Stream inside the mapping function.
  • Using map instead of flatMap when you want to flatten nested streams.
  • Not understanding that flatMap flattens one level of nesting only.

Here is an example showing the wrong and right way:

java
import java.util.*;
import java.util.stream.*;

public class FlatMapPitfall {
    public static void main(String[] args) {
        List<List<String>> listOfLists = Arrays.asList(
            Arrays.asList("a", "b"),
            Arrays.asList("c", "d")
        );

        // Wrong: map returns Stream<Stream<String>>, not flattened
        listOfLists.stream()
            .map(list -> list.stream())
            .forEach(System.out::println); // prints Stream objects, not strings

        System.out.println("--- Correct ---");

        // Right: flatMap flattens to Stream<String>
        listOfLists.stream()
            .flatMap(list -> list.stream())
            .forEach(System.out::println); // prints each string
    }
}
Output
java.util.stream.ReferencePipeline$Head@<hashcode> java.util.stream.ReferencePipeline$Head@<hashcode> --- Correct --- a b c d
📊

Quick Reference

  • Use flatMap when you have nested collections and want a single stream of all elements.
  • Mapping function must return a Stream, not a collection or array.
  • flatMap flattens one level of nested streams.
  • Use map if you want to keep nested streams without flattening.

Key Takeaways

Use flatMap to flatten nested streams into a single stream for easier processing.
The mapping function inside flatMap must return a Stream, not a collection or array.
flatMap flattens only one level of nested streams, so deeper nesting requires multiple flatMaps.
Use map when you want to transform elements without flattening nested streams.
Common mistake: using map instead of flatMap leads to streams of streams, not flattened streams.