[英]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
的每個MyClass
的id
。
我努力了:
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));
另一種方法是將map
和collect
步驟融合在一起,在提供給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.