简体   繁体   中英

How to create the Map using Java8 Stream?

How to update the Map using java 8 streams ? As for now I am doing :

        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;
    }

I haven't tested it but I suspect your code is equivalent to:

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

(with the appropriate static Collectors imports).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM