Given a stream of lists 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]
Here’s how we’ll go about doing this.
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.
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.
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);}}