Java8 - Map新增的方法:computeIfAbsent

Java8 - Map新增的方法:computeIfAbsent

computeIfAbsent

这个方法是JDK8中Map类新增的一个方法,用来实现当一个KEY的值缺失的时候,使用给定的映射函数重新计算填充KEY的值并返回结果。computeIfAbsent 方法的JDK源码如下:

default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
    Objects.requireNonNull(mappingFunction);
    V v;
    // 尝试获取KEY的值,如果获取不到KEY
    if ((v = get(key)) == null) {
        V newValue;
        // 利用传入的计算函数,得到新的值
        if ((newValue = mappingFunction.apply(key)) != null) {
            // 将KEY的值填充为函数计算的结果
            put(key, newValue);
            // 返回计算的结果
            return newValue;
        }
    }
    // 如果KEY的值存在,则直接返回
    return v;
}


computeIfAbsent使用例子

Map<String, String> cache = new HashMap<>();
// 如果键的值不存在,则调用函数计算并将计算结果作为该KEY的值
final String key = "myKey";
cache.computeIfAbsent(key, s -> {
    System.out.println("根据" + s + "计算新的值");
    return "myCacheValue";
});
// 第一次get,会调用映射函数
System.out.println(cache.get(key));
// 第二次get,不会调用映射函数
System.out.println(cache.get(key));


程序输出结果如下:

根据myKey计算新的值
myCacheValue
myCacheValue


本文原文地址:https://blog.****.net/zebe1989/article/details/83053962