Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

java-8

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.

like image 620
Richard Fowler Avatar asked Feb 03 '17 09:02

Richard Fowler


People also ask

What happens if key is not present in map?

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.

What is the method that adds values to a map?

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.

What is put if absent?

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.

What does map return if key doesnt exist Java?

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.


2 Answers

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)      
}
like image 88
Ash Avatar answered Sep 28 '22 07:09

Ash


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.

like image 26
Konstantin Yovkov Avatar answered Sep 28 '22 07:09

Konstantin Yovkov