How to Flatten Streams using flatMap() method in Java 8

In this post, we will discuss 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 Stream of { {"A", "B", "C"}, {"D", "E", "F"} } to
{ "A", "B", "C", "D", "E", "F" }

 
flatMap() takes a mapping function which 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 same type

 

Download   Run Code

Output:

[A, B, C, D, E, F]

 

2. Flatten a Stream of two or more Arrays of same type

 

Download   Run Code

Output:

[A, B, C, D, E, F]

 

3. Flatten a Stream of two Lists of same type

 

Download   Run Code

Output:

[A, B, C, D, E, F]

 

4. Flatten a Stream of two or more Lists of same type

 

Download   Run Code

Output:

[A, B, C, D, E, F]

 

5. Flatten a Map containing List of items as values

 

Download   Run Code

Output:

[A, B, C, D, E, F]

 

flatMapToInt() –

We know that calling Stream.of() method on an int 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

Output:

[1, 2, 3, 4, 5]

 

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

 
Also See:

1. Flatten Stream in Java using Stream.concat() method

2. Flatten a Stream in Java 8 using forEach() method

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz