繁体   English   中英

加入两个java流

[英]Joining two java streams

我有两个这样的java列表:

"type 1" list:
[(id:1, type: 1, value: 100), (id:2, type: 1, value: 50), ...]
"type 2" list:
[(id:1, type: 2, value: 150), (id:2, type: 2, value: 70), ...]

我想要这样的东西:

Stream.concat(list1.stream(), list2.stream())
.parallel()
// I need to combine somehow items with the same id for following process
// ideally to have Tuple2(l1item, l2item) after that
.groupBy(x -> x.getId())
.map ((l1item, l2item) -> {
   // some processing
}).collect(Collectors.toList())

AFAIK可以通过以下方式实现:

Stream.concat(list1.stream(), list2.stream())
.collect(groupingBy(x -> x.getItem)).values().stream()
.map (listOftwo -> ....)

但我不想要那个中间地图。 有任何想法吗 ? 我可以使用任何库。

谢谢

如果我理解正确...有一个重载的groupingBy减少已经分组的元素,如下所示:

  Map<Boolean, Double> result = Arrays.asList("a", "b", "ag").stream()
            .collect(Collectors.groupingBy(elem -> elem.startsWith("a"), 
                    Collectors.averagingInt(String::length)));

    System.out.println(result); // {false=1.0, true=1.5}

这会对元素进行分组,然后对值应用另一个收集器,从而减少它们。

AbacusUtil提供的API可以完全按照您的要求执行:

Stream.concat(a, b).parallel().groupBy(x -> x.getId()).map(..);

声明:我是AbacusUtil的开发人员。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM