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]
- Flatten a Stream of Map in Java using forEach loop
- Flatten a Stream of Arrays in Java using forEach loop
- foreach() loop vs Stream foreach() vs Parallel Stream foreach()
- Stream forEach() method in Java with examples
- Difference between Stream.of() and Arrays.stream() method in Java
- Character Stream Vs Byte Stream in Java
- Foreach in C++ and Java
- Iterator vs Foreach In Java
- DoubleStream forEach() method in Java
- ArrayList forEach() method in Java
- Vector forEach() method in Java
- IntStream forEach() method in Java
- ArrayDeque forEach() method in Java
- LongStream forEach() method in Java
- CopyOnWriteArrayList 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 email@example.com. 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.