Putting a new value into a Map if not present, or adding it if it is

Richard Fowler :

I have a java.util.Map<Foo, Double> for a key-type class Foo. Let's call the instance of the map map.

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.

Currently I use

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

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.

Thank you.

Ash :

this is what the merge function on maps is for.

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

this can be reduced even further to

map.merge(foo, f, Double::sum)

it is basically the equivalent of

if(map.contains(foo)){
    double x = map.get(foo);
    map.put(foo, x + f)
} else {
    map.put(foo, f)      
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=452296&siteId=1