Flattening Nested Collections in Java
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Stream is used to computing elements as per the pipelined methods without altering the original value of the object. And, flattening means merging two or more collections into one. Consider the below illustration where we have an array including 3 arrays but after the flattening effect, we will have one result array with all the elements in three arrays.
Illustration:
Input : arr1[] = {{1,2,3,4},{5,6,7},{8,9}};
Processing : Flatening
Output : arr1[] = {1,2,3,4,5,6,7,8,9};Stream flatMap() method is used to flatten a Stream of collections to a stream of objects. The objects are combined from all the collections in the original stream. The flatMap() method is a one-to-many transformation to the elements of the stream and then flattening the resulting elements into a new stream. Basically Stream.flatMap() method helps to covert Stream<Collection<T>> to the Stream<T>.
Example 1: Flatten a stream of two arrays of the same type using the flatMap() method
Java
// Java Program to flatten a stream of same type two arrays// using flatMap() method // Importing input output classesimport java.io.*;// Importing Arrays and Stream classes // from java.util packageimport java.util.Arrays;import java.util.stream.Stream; // Main classclass GFG { // Method 1 // To flatten a stream of two arrays of the same type public static <T> Stream<T> flatten(T[] a, T[] b) { // Stream.flatMap() method coverts // Stream<Collection<T>> to the Stream<T> Stream<T> stream = Stream.of(a, b).flatMap(Arrays::stream); // Returns the desired stream return stream; } // Method 2 // Main driver method public static void main(String[] args) { // Input array of strings // Array 1 has uppercase characters String[] a = { "A", "B", "C" }; // Array 2 has lowercase characters String[] b = { "i", "J", "K" }; // Calling the above method in the main() method String[] s = flatten(a, b).toArray(String[] ::new); // Return string representation of contents // of integer array System.out.println(Arrays.toString(s)); }} |
[A, B, C, i, J, K]
Example 2: Flatten a stream of two lists of the same type
Java
// Java Program to Flatten a stream of Two Lists// of the same type // Importing required librariesimport java.io.*;import java.util.Arrays;import java.util.Collection;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; // Main classpublic class GFG { // Method 1 // Flatten a stream of two lists of the same type public static <T> Stream<T> flatten(List<T> a, List<T> b) { // Stream.flatMap() method coverts // Stream<Collection<T>> to the Stream<T> // using flatMap(x -> x.stream()) Stream<T> stream = Stream.of(a, b).flatMap(List::stream); // Return the desired stream return stream; } // Method 2 // Main drier method public static void main(String[] args) { // Input Lists // List 1 List<String> a = Arrays.asList("Ma", "Rs", "Xy"); // List 2 List<String> b = Arrays.asList("Jw", "Pi", "Br"); // Calling the method 1 and storing it in a single // list List<String> s = flatten(a, b).collect(Collectors.toList()); // Print all the elements in above List object System.out.println(s); }} |
[Ma, Rs, Xy, Jw, Pi, Br]
Example 3: Flatten a map containing a list of items as values using flatMap() method
Java
// Java Program to Flatten a map containing a list of items// as values using flatMap() method // Importing input output classesimport java.io.*;// Importing desired classes from java.util packageimport java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream; // Main classpublic class GFG { // Method 1 // To flatten a map containing a list of items as values public static <T> Stream<T> flatten(Collection<List<T> > values) { // Stream.flatMap() method coverts // Stream<Collection<T>> to the Stream<T> Stream<T> stream = values.stream().flatMap(x -> x.stream()); // Return the desired stream return stream; } // Method 2 // Main driver method public static void main(String[] args) { // Creating an object of Map class // Declaring object of integer and string type Map<Integer, List<String> > map = new HashMap<>(); // Adding elements to the above Map object // Custom input entries map.put(1, Arrays.asList("1", "2", "3")); map.put(2, Arrays.asList("4", "5", "6")); // Creating a List class object holding all elements // after flatenning List<String> s = flatten(map.values()) .collect(Collectors.toList()); // Print and display the above List object System.out.println(s); }} |
[1, 2, 3, 4, 5, 6]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.


