Stream flatMap() in Java with examples
Last Updated :
11 Mar, 2025
Stream flatMap(Function mapper) returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Stream flatMap(Function mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance, and after they finish their processing, they give a Stream instance as output.
Note: Each mapped stream is closed after its contents have been placed into this stream. If a mapped stream is null, an empty stream is used, instead.
flatMap() V/s map()
- map() transforms each element of a stream into another object, resulting in a stream of the same size as the input. It's used for one-to-one transformations.
- flatMap() transforms each element of a stream into zero or more elements, potentially changing the size of the stream. It's used for one-to-many transformations and flattening nested structures.
Syntax:
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
Where R is the element type of the new stream.Stream is an interface, and T is the type of stream elements. Mapper is a stateless function that is applied to each element, and the function returns the new stream.
Example 1: Flattening a Stream of Lists
flatMap() function to flatten a stream of lists into a stream of elements.
Java
// Java code for Stream flatMap
// to flatten a stream of lists into a stream of elements
import java.util.*;
import java.util.stream.Stream;
class Geeks
{
// Driver code
public static void main(String[] args)
{
// Creating a List of Lists
List<List<String>> listOfLists = Arrays.asList(
Arrays.asList("Geeks", "For"),
Arrays.asList("GeeksForGeeks", "A computer portal"),
Arrays.asList("Java", "Programming")
);
// Using Stream flatMap(Function mapper)
listOfLists.stream()
.flatMap(list -> list.stream())
.forEach(System.out::println);
}
}
OutputGeeks
For
GeeksForGeeks
A computer portal
Java
Programming
Explanation: Here, flatMap()
is used to flatten a stream of lists into a single stream of elements. Using map
instead would not achieve this flattening effect.
Example 2: Mapping Strings to Characters at Position 2
flatMap() function with the provided operation of mapping string with character at position 2.
Java
// Java code for Stream flatMap
// (Function mapper) to get a stream by
// replacing the stream with a mapped
// stream by applying the provided mapping function.
import java.util.*;
import java.util.stream.Stream;
class Geek
{
// Driver code
public static void main(String[] args) {
// Creating a List of Strings
List<String> list = Arrays.asList("Geeks", "GFG", "GeeksforGeeks", "gfg");
// Using Stream flatMap(Function mapper)
list.stream()
.map(str -> str.charAt(2))
.forEach(System.out::println);
}
}
Explanation: In this case, flatMap
is used to create a stream of characters at position 2 from each string. If we used it map
, the result would be a stream of streams, not a flattened stream of characters.
How does flatMap() work ?
As already discussed in the post that flatMap() is the combination of a map and a flat operation i.e. it first applies the map function and then flattens the result. Let us consider some examples to understand what exactly flattening a stream is.
Example 1:
The list before flattening:
[ [2, 3, 5], [7, 11, 13], [17, 19, 23] ]
The list has 2 levels and consists of 3 small lists. After Flattening, it gets transformed into a "one level" structure as shown :
[ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]
Example 2:
The list before flattening :
[ ["G", "E", "E"], ["K", "S", "F"], ["O", "R", "G"], ["E", "E", "K", "S"] ]
The list has 3 levels and consists of 4 small lists. After Flattening, it gets transformed into a "one level" structure as shown :
["G", "E", "E", "K", "S", "F", "O", "R", "G", "E", "E", "K", "S"]
In short, we can say that if there is a Stream of List of <<Data Type>> before flattening, then on applying flatMap(), Stream of <<Data Type>> is returned after flattening.
Flattening Nested Lists
Java
import java.util.*;
import java.util.stream.Collectors;
class Geeks
{
public static void main(String[] args) {
// Creating a list of prime numbers
List<Integer> PrimeNumbers = Arrays.asList(5, 7, 11, 13);
// Creating a list of odd numbers
List<Integer> OddNumbers = Arrays.asList(1, 3, 5);
// Creating a list of even numbers
List<Integer> EvenNumbers = Arrays.asList(2, 4, 6, 8);
// Combining the above lists into a list of lists
List<List<Integer>> listOfListofInts = Arrays.asList(PrimeNumbers, OddNumbers, EvenNumbers);
// Printing the structure before flattening
System.out.println("The Structure before flattening is : " + listOfListofInts);
// Flattening the list of lists into a single list using flatMap
List<Integer> listofInts = listOfListofInts.stream()
.flatMap(list -> list.stream())
.collect(Collectors.toList());
// Printing the structure after flattening
System.out.println("The Structure after flattening is : " + listofInts);
}
}
OutputThe Structure before flattening is : [[5, 7, 11, 13], [1, 3, 5], [2, 4, 6, 8]]
The Structure after flattening is : [5, 7, 11, 13, 1, 3, 5, 2, 4, 6, 8]
Explanation: This example demonstrates how flatMap
flattens nested lists into a single list. Using map
would keep the nested structure intact.