繁体   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