Close

Java 8 Streams - Collectors.flatMapping() Examples

Java 8 Streams Java Java API 


Class:

java.util.stream.Collectors

java.lang.Objectjava.lang.Objectjava.util.stream.Collectorsjava.util.stream.CollectorsLogicBig

Method:

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

Adapts a Collector accepting elements of type U to one accepting elements of type T by applying a flat mapping function to each input element before accumulation. The flat mapping function maps an input element to a java.util.stream covering zero or more output elements that are then accumulated downstream.

Since Java 9.


Examples


package com.logicbig.example.collectors;

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

public class FlatMappingExample {

public static void main(String... args) {
List<Integer> list = Stream.of(List.of(1, 2, 3, 4), List.of(5, 6, 7, 8))
.collect(
Collectors.flatMapping(
l -> l.stream()
.filter(i -> i % 2 == 0),
Collectors.toList()
)
);
System.out.println(list);
}
}

Output

[2, 4, 6, 8]
Original Post




Following example groups the lists of stream by the lists' sizes and maps each list to the flat elements of integer which are only divisible by 2:

package com.logicbig.example.collectors;

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

public class FlatMappingExample2 {

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]}
Original Post




See Also