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
forEachloop to convert each inner list in the outer list to a stream using thestream()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
arrfrom listsa,b, andc. -
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
forEachloop to convert each lista,b, andcinarrto stream and storing it instreamList. -
Line 33: Converting
streamListto stream and then flattening the streams using thecollect()method, and assigning it toflatList. -
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 flattenedList<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 arrList<List<Integer> > arr = new ArrayList<List<Integer> >();arr.add(a);arr.add(b);arr.add(c);//declare a list that store flattened stream of listsList<Integer> flatList = new ArrayList<Integer>();//declare a list that contain streamsList<Integer> streamList = new ArrayList<>();//for each loop to convert list in arr to stream and add the stream to streamListfor (List<Integer> list : arr) {list.stream().forEach(streamList::add);}//flatten the stream using collect methodflatList = streamList.stream().collect(Collectors.toList());//print the unflattenned and flattenned list repectivelySystem.out.println("Unflatenned stream: " + arr);System.out.println("Flatenned list: " + flatList);}}