Java 8 Stream API-用Java 8重写的Java 9 Collectors.flatMapping [英] Java 8 Stream API - Java 9 Collectors.flatMapping rewritten in Java 8
问题描述
List<List<Integer>> list = Arrays.asList(
Arrays.asList(1, 2, 3, 4, 5, 6),
Arrays.asList(7, 8, 9, 10));
Map<Integer, List<Integer>> map =list.stream()
.collect(Collectors.groupingBy(
Collection::size,
Collectors.flatMapping(
l -> l.stream().filter(i -> i % 2 == 0),
Collectors.toList())));
{4 = [8,10],6 = [2,4,6]}
{4=[8, 10], 6=[2, 4, 6]}
仅使用 3 个收集器,这是一种相当优雅的方法.我需要在java-8 尚不支持.我尝试使用 6 收集器,该收集器使用范围很广,我无法找出减少使用它们的方法:
This is a fairly elegant way using just 3 collectors. I need to rewrite the collector in java-8 where is not yet supported. My attempt use 6 Collectors that is quite an extensive usage and I am not able to figure out a way using less of them:
Map<Integer, List<Integer>> map = list.stream()
.collect(Collectors.groupingBy(
Collection::size,
Collectors.collectingAndThen(
Collectors.mapping(
l -> l.stream().filter(i -> i % 2 == 0).collect(Collectors.toList()),
Collectors.toList()),
i -> i.stream().flatMap(j -> j.stream()).collect(Collectors.toList()))));
Is there a shorter better way using solely java-8?
推荐答案
对于这种特殊情况,我想这将是一个更简单的版本:
For just this particular case, I guess this would be a simpler version:
Map<Integer, List<Integer>> map =
list.stream()
.collect(Collectors.toMap(
Collection::size,
x -> x.stream().filter(y -> y % 2 == 0).collect(Collectors.toList())
));
如果要合并(两个具有相同大小的集合),我将添加一个非常简单的merge
函数:
If there would be merging involved (two collections that would have the same size), I would add a merge
function that is pretty trivial:
Map<Integer, List<Integer>> map =
list.stream()
.collect(Collectors.toMap(
Collection::size,
x -> x.stream().filter(y -> y % 2 == 0).collect(Collectors.toCollection(ArrayList::new)),
(left, right) -> {
left.addAll(right);
return left;
}
));
否则,我在此评论中同意Michael的观点,将其移植回java-8并不难.
Otherwise, I agree with Michael in this comment, this is not that hard to back-port to java-8.
这篇关于Java 8 Stream API-用Java 8重写的Java 9 Collectors.flatMapping的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!