在JAVA8之前我们一般像这样统计:
Map<String, Integer> counter = new HashMap<>();
//before Java 8
for (String word : words) {
if (counter.containsKey(word)) {
counter.put(word, counter.get(word) + 1);
} else {
counter.put(word, 1);
}
}
JAVA8 之后,我们可以这样统计:
words.forEach(word -> {
counter.putIfAbsent(word, 0);
counter.compute(word, (w, count) -> count + 1);
});
其中:
putIfAbsent 功能和put类似,区别在于当key相同时put 会覆盖value值,putIfAbsent不会
compute:如果key不存在或者key对应的value为null的话,则其value都是null。否则就是key对应的value值
所以我们可以用逗号表达式做空判断忽略putIfAbsent,将代码精简为一行,如下:
words.forEach(word -> counter.compute(word, (w, count) -> count == null ? 1 : count + 1));
使用map.merge() 可以更精简:
words.forEach(word -> counter.merge(word, 1, (count, one) -> count + one));
在使用双冒号表达式精简下:
words.forEach(word -> counter.merge(word, 1, Integer::sum));
参考: