Importance of Collectors.flatMapping() method in Java 9?


In Java 9, a new method added to the Collectors class: flatMapping(). It is similar to the Collectors.mapping() method in which the flatMapping() method allows us to handle nested collections. The Collectors.flatMapping() method takes a function to be applied to input elements and a collector to accumulate the elements passed through the function. Unlike the Collectors.mapping() method, the Collectors.flatMapping() method deals with a stream of elements that allows us to get rid of unnecessary intermediary collections.

Syntax

public static <T,U,A,R> Collector<T,?,R> flatMapping(Function<? super T,? extends Stream<? extends U>> mapper, Collector<? super U,A,R> downstream)

Example

import java.util.stream.Collectors;
import java.util.Stream;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class FlatMappingMethodTest {
   public static void main(String args[]) {
      Map<Integer, List<Integer>> map = Stream.of(List.of(1, 2, 3, 4, 5, 6), List.of(7, 8, 9, 10))
                                              .collect(Collectors.groupingBy(
                                                              Collection::size,
                                                              Collectors.flatMapping(
                                                                     l -> l.stream()
                                                                           .filter(i -> i % 2 == 0),
                                                                     Collectors.toList())
                                                       )
                                               );
      System.out.println(map);
   }
}

Output

{4=[8, 10], 6=[2, 4, 6]}

Updated on: 05-Mar-2020

244 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements