Lambda填充地图 [英] Lambda to populate Map
本文介绍了Lambda填充地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试用字词及其出现次数填充地图。我正在尝试编写一个lambda来执行此操作,如下所示:
I am trying to fill up a map with words and the number of their occurrences. I am trying to write a lambda to do it, like so:
Consumer<String> wordCount = word -> map.computeIfAbsent(word, (w) -> (new Integer(1) + 1).intValue());
map
是 Map< String,Integer>
。它应该只是将地图中的单词作为键插入,如果它不存在,如果它存在,它应该将其整数值增加1.这一个在语法方面是不正确的。
map
is Map<String, Integer>
. It should just insert the word in the map as a key if it is absent and if it is present it should increase its integer value by 1. This one is not correct syntax-wise.
推荐答案
您不能使用 computeIfAbsent
递增计数,因为它只会在第一次计算。
You can't increment the count using computeIfAbsent
, since it will only be computed the first time.
你可能意味着:
map.compute(word, (w, i) -> i == null ? 1 : i + 1);
这篇关于Lambda填充地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文