Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method.
Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ] Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ] Output: [G, e, e, k, s, F, o, r]
- Get the Lists in the form of 2D list.
- Create an empty list to collect the flattened elements.
- With the help of forEach loop, convert each elements of the list into stream and add it to the list
- Now convert this list into stream using stream() method.
- Now flatten the stream by converting it into list using collect() method.
Below is the implementation of the above approach:
Example 1: Using lists of integer.
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 2: Using lists of Characters.
[G, e, e, k, s, F, o, r, G, e, e, k, s]
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- foreach() loop vs Stream foreach() vs Parallel Stream foreach()
- Flatten a Stream of Arrays in Java using forEach loop
- Flatten a Stream of Map in Java using forEach loop
- Java Program to Iterate Over Arrays Using for and foreach Loop
- Stream forEach() method in Java with examples
- Character Stream Vs Byte Stream in Java
- Difference between Stream.of() and Arrays.stream() method in Java
- Foreach in C++ and Java
- Iterator vs Foreach In Java
- IntStream forEach() method in Java
- DoubleStream forEach() method in Java
- LongStream forEach() method in Java
- Iterable forEach() method in Java with Examples
- ArrayDeque forEach() method in Java
- ArrayList forEach() method in Java
- Vector forEach() method in Java
- HashTable forEach() method in Java with Examples
- LinkedTransferQueue forEach() method in Java with Examples
- LinkedBlockingDeque forEach() method in Java with Examples
- CopyOnWriteArraySet forEach() method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.