We have already covered how to flatten a stream using flatMap() and concat() methods in Java. This post will flatten an array or a list using the Stream.forEach() method in Java 8 and above.

1. Flattening Arrays

We can flatten two or more arrays of the same type using the forEach() method in Java. The idea is to create an empty list to store the flattened elements, and use a forEach() loop to iterate over the arrays and convert each array into a stream using the Arrays.stream() method. Then, using the forEach() method again, add each element of the stream to the list. Finally, we can convert the list into an array using the toArray() method. Here is a complete example:

Download  Run Code

2. Flattening Lists

To flatten two or more lists of the same type using the forEach() method in Java, we can create a new list that will store the flattened elements. Then use a nested forEach() loop to iterate over each list and add its elements to the new list. Here is an example of how to flatten multiple lists of characters using this method:

Download  Run Code

 
If we have a map containing a list of items as values, we can create an empty list to collect the flattened elements and use the forEach() method to iterate over the map values, which are lists of items. Then use a nested forEach() loop to iterate over each list and add its elements to the empty list. Here is an example of how to do this:

Download  Run Code

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