Java8 computeIfAbsent

源码如下:

default V computeIfAbsent(K key,
            Function<? super K, ? extends V> mappingFunction) {
        Objects.requireNonNull(mappingFunction);
        V v;
        if ((v = get(key)) == null) {
            V newValue;
            if ((newValue = mappingFunction.apply(key)) != null) {
                put(key, newValue);
                return newValue;
            }
        }

        return v;
    }

用法

map.computeIfAbsent(key, k -> new Value(f(k)));

map.computeIfAbsent(key, k -> new HashSet<V>()).add(v);


猜你喜欢

转载自www.cnblogs.com/inspirationBoom/p/9994932.html