簡體   English   中英

java streams - 如何使用鍵上的條件來平移集合映射中的所有值

[英]java streams - how to flat all values from map of collections using condition on the key

我有一張地圖。 讓我們說吧

Map<Long, List<MyObj>> 

我想在所有MyObj中創建一個長數組,其中鍵(long)在另一個set()中找到

anotherSet.contains(long)

使用java流。

我試過了

map.entrySet()
   .stream()
   .filter(e->anotherSet(e.getKey()))
   .flatMap(e.getValue)
   .collect(Collectors.toList);

但它甚至沒有編譯

你有一些語法錯誤。

這應該產生你想要的List

List<MyObj> filteredList = 
    map.entrySet()
       .stream()
       .filter(e->anotherSet.contains(e.getKey())) // you forgot contains
       .flatMap(e-> e.getValue().stream()) // flatMap requires a Function that 
                                           // produces a Stream
       .collect(Collectors.toList()); // you forgot ()

如果要生成數組而不是List ,請使用:

MyObj[] filteredArray = 
    map.entrySet()
       .stream()
       .filter(e->anotherSet.contains(e.getKey()))
       .flatMap(e-> e.getValue().stream())
       .toArray(MyObj[]::new);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM