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.
If the key is not present in the map, get() returns null. The get() method returns the value almost instantly, even if the map contains 100 million key/value pairs.
The standard solution to add values to a map is using the put() method, which associates the specified value with the specified key in the map. Note that if the map already contains a mapping corresponding to the specified key, the old value will be replaced by the specified value.
Overview. The putIfAbsent method adds the key-value pair to the map if the key is not present in the map. If the key is already present, then it skips the operation.
Return Value: This method returns null (if there was no mapping with the provided key before or it was mapped to a null value) or current value associated with the provided key.
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)
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With