I have a java.util.Map
for a key-type class Foo
. Let\'s call the instance of the map map
.
I want to add {
You can do:
map.put(foo, f + map.getOrDefault(foo, 0d));
The value here will be the one that corresponds to foo
if present in the Map
or 0d
, otherwise.
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)
}