簡體   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