Given a Stream of Map in Java, the task is to Flatten the Stream using forEach() method.
Examples:
Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]}
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Input: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e, k, s]}
Output: [G, e, e, k, s, F, o, r]
Approach:
- Get the Map to be flattened.
- Create an empty list to collect the flattened elements.
- With the help of forEach loop, convert each elements of the Map values into stream and add it to the list
- This list is the required flattened map.
Below is the implementation of the above approach:
Example 1: Using lists of integer.
import java.util.*;
import java.util.stream.*;
class GFG {
public static <T> List<T> flattenStream(Collection<List<T> > lists)
{
List<T> finalList = new ArrayList<>();
for (List<T> list : lists) {
list.stream()
.forEach(finalList::add);
}
return finalList;
}
public static void main(String[] args)
{
Map<Integer, List<Integer> > map = new HashMap<>();
map.put(1, Arrays.asList(1, 2));
map.put(2, Arrays.asList(3, 4, 5, 6));
map.put(3, Arrays.asList(7, 8, 9));
List<Integer> flatList = flattenStream(map.values());
System.out.println(flatList);
}
}
|
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 2: Using lists of Characters.
import java.util.*;
import java.util.stream.*;
class GFG {
public static <T> List<T> flattenStream(Collection<List<T> > lists)
{
List<T> finalList = new ArrayList<>();
for (List<T> list : lists) {
list.stream()
.forEach(finalList::add);
}
return finalList;
}
public static void main(String[] args)
{
Map<Integer, List<Character> > map = new HashMap<>();
map.put(1, Arrays.asList('G', 'e', 'e', 'k', 's'));
map.put(2, Arrays.asList('F', 'o', 'r'));
map.put(3, Arrays.asList('G', 'e', 'e', 'k', 's'));
List<Character> flatList = flattenStream(map.values());
System.out.println(flatList);
}
}
|
Output:
[G, e, e, k, s, F, o, r, G, e, e, k, s]
Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
11 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...