Java – if it doesn’t exist, add a new value to the map, or add it

I have a Java util. Map < foo, double > foo of a key class Let's call an example of a map

I want to add {foo, f} (foo is an instance of Foo and F is double) But if the key foo already exists, I want to add f to the current value in the map

Currently I use

Double current = map.get(foo);
f += current == null ? 0.0 : current;
map.put(foo,f);

But is there a fashionable way in Java 8, such as using map #merge and double:: sum?

Unfortunately, I can't imagine it

thank you.

Solution

This is the merge function on the map

map.merge(foo,f,(f1,f2) -> f1 + f2)

This can be further reduced

map.merge(foo,Double::sum)

It's basically equivalent to

if(map.contains(foo)){
    double x = map.get(foo);
    map.put(foo,x + f)
} else {
    map.put(foo,f)      
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>