简体   繁体   中英

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

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

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

对于不熟悉merge方法的人:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM