我有两个这样的 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())
据我所知,它可以通过以下方式实现:
Stream.concat(list1.stream(), list2.stream())
.collect(groupingBy(x -> x.getItem)).values().stream()
.map (listOftwo -> ....)
但我不想要那个中间 map 。有任何想法吗 ?我可以使用任何库。
谢谢
最佳答案
如果我理解正确的话......有一个重载的 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}
这对元素进行分组,然后对值应用另一个收集器,减少它们。
关于java - 加入两个java流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40888550/