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 streamList that will store streams.
  • Line 21 to 24: Us the for-each loop to convert each array in arr to stream and store it in streamList.
  • Line 27: Convert the streamList to stream and then flatten the streams, using the toArray() method, and assign it to flattenArray.
  • Line 30: Print the original 2D input array
  • Line 31: Print the 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 flattened
Integer[][] arr = {
{ 1, 2 },
{ 3, 4, 5, 6 },
{ 7, 8, 9 }
};;
//declare a list that contain streams
List<Integer> streamList = new ArrayList<>();
//for each loop to convert array in arr to stream and add the stream to streamList
for (Integer[] array : arr) {
Arrays.stream(array)
.forEach(streamList::add);
}
//flatten the stream using toArray method
Integer[] flattenArray = streamList.stream().toArray(Integer[] ::new);
//print the flattend arrays
System.out.println("Input: " + Arrays.deepToString(arr));
System.out.println("Output: " + Arrays.toString(flattenArray));
}
}

Free Resources