簡體   English   中英

如何使用Java8 Stream創建Map?

[英]How to create the Map using Java8 Stream?

如何使用Java 8流更新Map? 至於現在我正在做:

        Map<String, Integer> testMap = Maps.newHashMap();

        for(Map.Entry<String,Integer> testEntrySet : testCounts.entrySet()) {
            String name = Utils.cleanName(testEntrySet.getKey());

            if(testMap.containsKey(name)) {
                testMap.put(name, testMap.get(name) +
                        testCounts.get(testEntrySet.getKey()));
            } else {
                testMap.put(name, testCounts.get(testEntrySet.getKey()));
            }

        }
        return testMap;
    }

我尚未測試過,但我懷疑您的代碼等同於:

return testCounts.entrySet().stream()
        .collect(groupingBy(e -> Utils.cleanName(e.getKey()),
                            summingInt(e -> e.getValue())));

(帶有適當的靜態Collectors導入)。

暫無
暫無

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

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