Java 9中Collectors.flatMapping()方法的重要性?
在Java9中,向Collectors类添加了一个新方法:flatMapping()。它类似于Collectors.mapping()方法,其中flatMapping()方法允许我们处理嵌套的集合。Collectors.flatMapping()方法需要的功能将被施加到输入元件和集电极积累通过功能传递的元件。与Collectors.mapping()方法不同,Collectors.flatMapping()方法处理的元素流使我们能够摆脱不必要的中介集合。
语法
public static <T,U,A,R> Collector<T,?,R> flatMapping(Function<? super T,? extends Stream<? extends U>> mapper, Collector<? super U,A,R> downstream)
示例
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); } }
输出结果
{4=[8, 10], 6=[2, 4, 6]}