簡體   English   中英

Java 8流圖 <Long, List<MyClass> &gt;到地圖 <Long, Set<Long> &gt;

[英]Java 8 stream Map<Long, List<MyClass>> to Map<Long, Set<Long>>

我想在Map<Long, Set<Long>>中轉換(使用Java 8流) Map<Long, List<MyClass>> ,其中Set<Long>表示List的每個MyClassid

我努力了:

myFirstMap.entrySet().stream()
      .map(e -> e.getValue().stream()
          .map(MyClass::getId)
          .collect(Collectors.toSet()))

但是我看不到如何得到結果。

您正在將Map.Entry實例映射到Set<Long>實例,這意味着失去對原始地圖鍵的跟蹤,這使得無法將它們收集到具有相同鍵的新地圖中。

第一個選項是將Map.Entry<Long, List<MyClass>>實例映射到Map.Entry<Long, Set<Long>>實例,然后將條目收集到新的映射中:

Map<Long, Set<Long>> result=
    myFirstMap.entrySet().stream()
        .map(e -> new AbstractMap.SimpleImmutableEntry<>(e.getKey(),
               e.getValue().stream().map(MyClass::getId).collect(Collectors.toSet())))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

另一種方法是將mapcollect步驟融合在一起,在提供給toMap收集器的value函數中進行toMap

Map<Long, Set<Long>> result=
    myFirstMap.entrySet().stream().collect(Collectors.toMap(
        Map.Entry::getKey,
        e -> e.getValue().stream().map(MyClass::getId).collect(Collectors.toSet())));

這樣,您可以避免創建新的Map.Entry實例並獲得更簡潔的代碼,但是,由於無法在其間鏈接其他流操作,因此靈活性Map.Entry

另一種沒有外部Stream開銷的解決方案是使用Map.forEach()如下所示:

Map<Long,Set<Long>> result = new HashMap<>();
myFirstMap.forEach((k,v) -> 
    result.put(k, v.stream()
        .map(MyClass::getId)
        .collect(Collectors.toSet())));

這實際上只是一種方便的方法:

Map<Long,Set<Long>> result = new HashMap<>();
for (Map.Entry<Long, List<MyClass>> entry : myFirstMap.entrySet()) {
    result.put(entry.getKey(), entry.getValue().stream()
        .map(MyClass::getId)
        .collect(Collectors.toSet()));
}

暫無
暫無

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

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