Java 8 merge multiple collections using flatmap

www‮.‬lautturi.com
Java 8 merge multiple collections using flatmap

In Java 8 and later, you can use the flatMap method of the Stream interface to merge multiple Collection objects into a single Stream, and then use the collect method to convert the resulting Stream into a new Collection.

To merge multiple Collection objects using the flatMap method, you can use the following syntax:

List<Type> mergedList = collections.stream()
    .flatMap(Collection::stream)
    .collect(Collectors.toList());

Here, Type is the type of the elements in the Collection objects, collections is a List or other Collection of Collection objects, and mergedList is the resulting List containing the merged elements of the Collection objects.

Here is an example of how you can use the flatMap and collect methods to merge multiple List objects into a single List:

import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;

public class MyClass {
    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("apple", "banana");
        List<String> list2 = Arrays.asList("cherry", "mango");
        List<String> list3 = Arrays.asList("orange", "grape");
        List<List<String>> collections = Arrays.asList(list1, list2, list3);

        List<String> mergedList = collections.stream()
            .flatMap(List::stream)
            .collect(Collectors.toList());

        System.out.println(mergedList); // Outputs ["apple", "banana", "cherry", "mango", "orange", "grape"]
    }
}

In this example, the collectionsList contains three List objects: list1, list2, and list3.

The flatMap method flattens the List objects into a single Stream of elements, and the collect method converts the Stream into a new List containing the merged elements.

Created Time:2017-11-01 22:29:44  Author:lautturi