Reputation: 1624
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;
}
Upvotes: 1
Views: 825
Reputation: 328568
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).
Upvotes: 5