This post will discuss the flatMap() method in Java, which is used to flatten streams in Java.

We know that streams in Java is capable of holding different types of data. For instance,
 

  1. Stream<T> – Stream where each element is an object.
  2. IntStream, DoubleStream, or LongStream – Stream where each element is a primitive data-type.
  3. Stream<int[]> – Stream where each element is a primitive array.
  4. Stream<T[]> – Stream where each element is an object array.
  5. Stream<List<T>> – Stream where each element is a list.
  6. Stream<Collection<T>> – Stream where each element is a Collection.

 
The flatMap() method can be used for flattening streams in Java, as shown below:

Stream<T[]> –> Stream<T>

Stream<List<T>> –> Stream<T>

 
Basically, a flatMap() can convert a stream of { {"A", "B", "C"}, {"D", "E", "F"} } to
{ "A", "B", "C", "D", "E", "F" }

 
The flatMap() takes a mapping method that will be applied to each element of the stream to facilitate the flattening of the stream. Let’s now explore various problems in Java that can be solved by flattening a stream of arrays or list into a single continuous stream:

1. Flatten a stream of two arrays of the same type

Download  Run Code

2. Flatten a stream of two or more arrays of the same type

Download  Run Code

3. Flatten a stream of two lists of the same type

Download  Run Code

4. Flatten a stream of two or more lists of the same type

Download  Run Code

5. Flatten a map containing a list of items as values

Download  Run Code

 
This is equivalent to:

Download  Run Code

Using flatMapToInt()

We know that calling Stream.of() method on a primitive integer array returns Stream<int[]>. We can use flatMapToInt() method to convert a stream of primitive arrays Stream<int[]> to IntStream before consuming, as shown below:

Download  Run Code

 
Similarly, flatMapToDouble() can be used to flatten Stream<double[]> to DoubleStream and flatMapToLong() for flattening Stream<long[]> to LongStream.

That’s all about flattening a Java Stream using the flatMap() method.

 
Also See:

Flatten Stream of arrays or lists in Java using Stream.concat() method

Flatten a Stream in Java 8 using the forEach() method