ConcurrentHashMap JDK 8 when to use computeIfPresent

后端 未结 4 1331
粉色の甜心
粉色の甜心 2021-02-01 05:25

The new version of Concurrent Hash Map of jdk 8 has two new Methods.

computeIfAbsent

computeIfPresent

putIfAbs

4条回答
  •  鱼传尺愫
    2021-02-01 06:17

    I've used computeIfPresent as a null-safe way to fetch lowercase values from a map of strings.

    String s = fields.computeIfPresent("foo", (k,v) -> v.toLowerCase())
    

    Before computeIfPresent was available I'd have to do this:

    String s = map.get("foo");
    if (s != null) {
        s = s.toLowerCase();
    }
    

    Or this:

    String s = map.containsKey("foo") ? map.get("foo").toLowerCase() : null;
    

提交回复
热议问题