Given a stream of arrays in Java, the task is to flatten the stream using the forEach()
method.
Input: {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }}
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
stream()
method and add to the list.stream()
method.toArray()
method, and store it in the new array.In the following code snippet:
arr
.streamList
that will store streams.for-each
loop to convert each array in arr
to stream and store it in streamList
.streamList
to stream and then flatten the streams, using the toArray()
method, and assign it to flattenArray
.flattenArray
that contains flattened elements.import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.*;class Solution {public static void main( String args[] ) {//declare and initialize the 2D array that needs to be flattenedInteger[][] arr = {{ 1, 2 },{ 3, 4, 5, 6 },{ 7, 8, 9 }};;//declare a list that contain streamsList<Integer> streamList = new ArrayList<>();//for each loop to convert array in arr to stream and add the stream to streamListfor (Integer[] array : arr) {Arrays.stream(array).forEach(streamList::add);}//flatten the stream using toArray methodInteger[] flattenArray = streamList.stream().toArray(Integer[] ::new);//print the flattend arraysSystem.out.println("Input: " + Arrays.deepToString(arr));System.out.println("Output: " + Arrays.toString(flattenArray));}}