如果不存在,则将新值放入Map中,如果不存在则添加它 [英] Putting a new value into a Map if not present, or adding it if it is

查看:2719
本文介绍了如果不存在,则将新值放入Map中,如果不存在则添加它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于键类型 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中,如果不存在则添加它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆