对于键类型 Foo ,我有 java.util.Map< Foo,Double> 。让我们调用地图的实例 map 。
I have a java.util.Map<Foo, Double> for a key-type class Foo. Let's call the instance of the map map.
我想添加{ foo , f }( foo 是 Foo的实例和 f a Double )。但是如果键 foo 已经存在,我想将 f 加到该地图中的当前值。
I want to add {foo, f} (foo is an instance of Foo, and f a Double) to that map. But if the key foo is already present I want to sum f to the current value in that map.
目前我使用
Double current = map.get(foo); f += current == null ? 0.0 : current; map.put(foo, f);但在Java 8中是否有一种时髦的方法,例如使用 Map#merge , Double :: sum ?
But is there a funky way of doing this in Java 8, such as using Map#merge, and Double::sum?
很遗憾,我可以'弄明白。
Regrettably I can't figure it out.
谢谢。
推荐答案这是地图上的合并功能是什么。
this is what the merge function on maps is for.
map.merge(foo, f, (f1, f2) -> f1 + f2)这可以进一步减少到
map.merge(foo, f, Double::sum)它基本上是相当于
if(map.contains(foo)){ double x = map.get(foo); map.put(foo, x + f) } else { map.put(foo, f) }更多推荐
如果不存在,则将新值放入Map中,如果不存在则添加它
发布评论