ZhaoGang
ZhaoGang

Reputation: 4915

Is there anything like getOrDefault when putting a value into the java8 map?

In java8, when getting some value from a map, we can write:

int keyCount=countMap.getOrDefault(key,0);

which is equal to:

if(countMap.contains(key)){
    keyCount=countMap.get(key);
}else{
    keyCount=0;
}

Problem is that is there any elegant way to replace below codes:

if(countMap.keySet().contains(key)){
    countMap.put(key,countMap.get(key)+1);
}else{
    countMap.put(key,1);
}

Upvotes: 2

Views: 1076

Answers (3)

ZhaoGang
ZhaoGang

Reputation: 4915

For those who are not familar with the merge method:

countMap.put(key, countMap.getOrDefault(key,0)+1);

Upvotes: 0

Naman
Naman

Reputation: 32008

As holger mentioned as well, you can simply use Map.merge as :

countMap.merge(key, 1, Integer::sum)

Notice the documentation states its implementation as well:

The default implementation is equivalent to performing the following steps for this map, then returning the current value or null if absent:

V oldValue = map.get(key);
V newValue = (oldValue == null) ? value :
             remappingFunction.apply(oldValue, value);
if (newValue == null)
    map.remove(key);
else
    map.put(key, newValue);

Upvotes: 2

Matthew Leidholm
Matthew Leidholm

Reputation: 4469

You are looking for the compute method, also added in Java 8. That method takes in the key you are using, as well as a BiFunction to compute what the new value should be, based on the key and the existing value. So in your case, it would like something like the following:

countMap.compute(key, (k, oldValue) -> oldValue == null ? 1 : oldValue + 1);

When the key you give does not yet exist in the map, the oldValue in the BiFunction will be null; if you return null in the BiFunction, nothing gets put into the map.

It takes a little getting used to, but it's a very powerful method once you get the hang of it. It may be more readable (though much more verbose) with a method reference instead of the inline lambda:

    countMap.compute(key, this::incrementOrSetToOne);

    // ... some other code ...

    private Integer incrementOrSetToOne(KeyType key, Integer oldValue) {
        return oldValue == null ? 1 : oldValue + 1;
    }

Upvotes: 0

Related Questions