Flatten Stream of Arrays or Lists in Java using Stream.concat() method

Java 8 Streams can holds different types of data. For example, Stream<T>, Stream<T[]>, Stream<List<T>> – all these are valid streams in Java 8.

We have seen in the previous post that flatMap() method can be used for flattening Streams in Java. In this post, we will flatten Stream of Arrays or Lists using Stream.concat() method in Java.


 

1. Flatten a Stream of two or more arrays in Java 8

 

Download   Run Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 

2. Flatten a Stream of two or more lists in Java 8

 

Download   Run Code

Output:

[1, 2, 3, 4, 5, 6, 7]

 

3. Flatten a Map containing List of items as values in Java 8

 

Download   Run Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

 
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

avatar
  Subscribe  
newest oldest most voted
Notify of
M R
Guest

why not just do:

public static Stream flatten(T[]... arrays){
return Arrays.stream(arrays).map(Arrays::stream).reduce(Stream::concat).get();
}
public static List combine(T[]... arrays){
return flatten(arrays).collect(Collectors.toList());
}