Map接口中的三个默认方法-compute、computeIfA

2022-01-31  本文已影响0人  M_lear

compute

    default V compute(K key,
            BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        V oldValue = get(key);

        V newValue = remappingFunction.apply(key, oldValue);
        if (newValue == null) {
            // delete mapping
            if (oldValue != null || containsKey(key)) {
                // something to remove
                remove(key);
                return null;
            } else {
                // nothing to do. Leave things as they were.
                return null;
            }
        } else {
            // add or replace old mapping
            put(key, newValue);
            return newValue;
        }
    }

入参:

  1. key
  2. (key, oldValue) -> newValue

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

入参:

  1. key
  2. key -> newValue

computeIfPresent

    default V computeIfPresent(K key,
            BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        V oldValue;
        if ((oldValue = get(key)) != null) {
            V newValue = remappingFunction.apply(key, oldValue);
            if (newValue != null) {
                put(key, newValue);
                return newValue;
            } else {
                remove(key);
                return null;
            }
        } else {
            return null;
        }
    }

入参:

  1. key
  2. (key, oldValue) -> newValue

区别

compute不管key存不存在,都计算newValue。
computeIfAbsent只在key不存在的时候计算newValue。
computeIfPresent只在key存在的时候计算newValue。

个人只用过computeIfAbsent。
使用场景:
value是一个集合时,常常是List。

Map<String, List<String>> map = new HashMap<>();
// 当key没有对应的ArrayList时,为key创建一个ArrayList
List<String> list = map.computeIfAbsent(key, a -> new ArrayList<>());

// 对list操作
list.add(string);
上一篇下一篇

猜你喜欢

热点阅读