How to flatten a stream of lists using a forEach loop in Java

Problem

Given a stream of lists 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

Here’s how we’ll go about doing this.

Approach

  • Declare and initialize the list in 2D form.

  • Declare an empty list to store flattened items.

  • Use a forEach loop to convert each inner list in the outer list to a stream using the stream() method, and add it to the outer list.

  • Convert the outer list to stream using the same stream() method.

  • Flatten the stream into a list, using the collect() method, and store it in the empty list declared above.

  • Print the unflattened and flattened list.

Implementation

Here’s the explanation of the code below:

  • Lines 9 - 18: Creating a list arr from lists a, b, and c.

  • Line 21: Declaring an empty list flatList, which will store the flattened elements.

  • Line 24: Declaring an empty list streamList, which will store a stream of lists.

  • Lines 27 - 30: Using the forEach loop to convert each list a, b, and c in arr to stream and storing it in streamList.

  • Line 33: Converting streamList to stream and then flattening the streams using the collect() method, and assigning it to flatList.

  • Line 36: Printing arr, the original 2D list.

  • Line 37: Printing flatList, the flat list containing the flattened elements of the stream.

Code

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 lists that needs to be flattened
List<Integer> a = Arrays.asList(1, 2);
List<Integer> b = Arrays.asList(3, 4, 5, 6);
List<Integer> c = Arrays.asList(7, 8, 9);
//adding List<Integer> to another list arr
List<List<Integer> > arr = new ArrayList<List<Integer> >();
arr.add(a);
arr.add(b);
arr.add(c);
//declare a list that store flattened stream of lists
List<Integer> flatList = new ArrayList<Integer>();
//declare a list that contain streams
List<Integer> streamList = new ArrayList<>();
//for each loop to convert list in arr to stream and add the stream to streamList
for (List<Integer> list : arr) {
list.stream()
.forEach(streamList::add);
}
//flatten the stream using collect method
flatList = streamList.stream().collect(Collectors.toList());
//print the unflattenned and flattenned list repectively
System.out.println("Unflatenned stream: " + arr);
System.out.println("Flatenned list: " + flatList);
}
}

Free Resources