How to flatten a stream of arrays using a forEach loop in Java
Problem
Given a stream of arrays in Java, the task is to flatten the stream using the forEach() method.
Example
Input: {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }}
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Solution
Approach
- Declare and initialize the 2D arrays.
- Declare an empty list to store streams.
- Use a forEach loop to convert each inner array in the outer array to stream using the
stream()method and add to the list. - Convert the list to stream using the
stream()method. - Flatten the stream into the list, using the
toArray()method, and store it in the new array. - Print the array.
Implementation
In the following code snippet:
- Line 10 to 14: Create a 2D array
arr. - Line 18: Declare an empty list
streamListthat will store streams. - Line 21 to 24: Us the
for-eachloop to convert each array inarrto stream and store it instreamList. - Line 27: Convert the
streamListto stream and then flatten the streams, using thetoArray()method, and assign it toflattenArray. - Line 30: Print the original 2D input array
- Line 31: Print the
flattenArraythat 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));}}