Reputation: 1367
I have two java lists like this:
"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), ...]
And I want something like that:
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 it can be implemented via:
Stream.concat(list1.stream(), list2.stream())
.collect(groupingBy(x -> x.getItem)).values().stream()
.map (listOftwo -> ....)
But I don't want that intermediate map. Any ideas ? I can use any library.
Thanks
Upvotes: 1
Views: 310
Reputation: 1254
abacus-common provides the APIs to do exactly what you want:
Stream.concat(a, b).parallel().groupBy(x -> x.getId()).map(..);
Declaration: I'm the developer of AbacusUtil.
Upvotes: 1
Reputation: 120848
If I understood you correctly... there's a overloaded groupingBy that reduces the already grouped elements, something like this:
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}
This groups the elements and then applies another Collector on the values, reducing them.
Upvotes: 2