简体   繁体   中英

Joining two java streams

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

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.

AbacusUtil 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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