Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
<strong>public static <T,U,A,R> Collector<T,?,R> flatMapping(Function<? super T,? extends Stream<? extends U><!--? super T,? extends Stream<? extends U-->> mapper, Collector<? super U,A,R><!--? super U,A,R--> downstream)</strong>
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[]) {
<strong> Map<Integer, List<Integer>></strong> map = <strong>Stream.of</strong>(<strong>List.of</strong>(1, 2, 3, 4, 5, 6), <strong>List.of</strong>(7, 8, 9, 10))
.<strong>collect</strong>(<strong>Collectors.groupingBy</strong>(
Collection::size,
<strong>Collectors.flatMapping</strong>(
l -> l.stream()
.filter(i -> i % 2 == 0),
<strong> Collectors.toList()</strong>)
)
);
System.out.println(map);
}
}
Output
<strong>{4=[8, 10], 6=[2, 4, 6]}</strong> Advertisements
