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

ZhaoGang :

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);
}
Naman :

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);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=152013&siteId=1