Java 17 Example Of flatMap Method

Let’s see example of flatMap. This method is part of the Stream API. We can use when we have nested collections but need only one level (we need to remove the nested collections ) and merge all the elements in one single collection.

Lets have a simple class Main:

package org.example;

import java.util.Collection;
import java.util.List;
import java.util.Set;

public class Main {
    public static void main(String[] args) {

        List<Set<String>> listWithSets = List.of(
                Set.of("chicken, duck, owl"),
                Set.of("cat, dog, elephant, mouse")
        );

        // Examples where we merge both the Sets in one List
       List<String> result =  listWithSets.stream().flatMap(set -> set.stream()).toList();
       System.out.println(result);

        List<String> result2 =  listWithSets.stream().flatMap(Collection::stream).toList();
        System.out.println(result2);

    }
}

The result is:

[chicken, duck, owl, cat, dog, elephant, mouse]
[chicken, duck, owl, cat, dog, elephant, mouse]

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.