Map中compute()、computeIfPresent()、computeIfAbsent()、merge()的使用以及原理

1. 总结

  1. compute():无论key是否存在,都会执行后面方法。若后面方法返回newValue为NULL,则会从Map中remove(key),若返回newValue不为NULL,则put(key,newValue),简单一句话:newValue有值则插入更新,无值就删除该key
  2. computeIfPresent(): 当key存在的时候,才会执行后面方法。
  3. computeIfAbsent(): 当key不存在的时候,才会执行后面方法。
  4. merge(key,value,function): 当key不存在的时候,直接put(key,value),若key存在,则执行function方法。

2. 代码例子以及源码解析:

1. compute()

  1. 代码例子

    public class demo {
        public static void main(String[] args) {
            Map<String, String> map = new HashMap<>();
            map.put("1", "1");
            map.put("2", "2");
            map.put("3", "3");
            // compute():无论key是否存在,都会执行BiFunction
            // 1. 当key不存在map时,则会存入map中
            // 2. 当value返回null时,会从map中remove掉该key
            // 3. 只要BiFunction返回值不为null,则都会put(key,newValue);
            map.compute("1", (k, v) -> null);
            map.compute("2", (k, v) -> k + "-" + v);
            map.compute("5", (k, v) -> k);
            System.out.println(map);
    
        }
    }
    
    

    在这里插入图片描述

2. 源码:

 default V compute(K key,
            BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        // 传入的Function不能为空
        Objects.requireNonNull(remappingFunction);
        // 先拿key对应的value
        V oldValue = get(key);
			 // 直接执行function里面的方法,无加任何条件
        V newValue = remappingFunction.apply(key, oldValue);
        // 若newValue返回是空
        if (newValue == null) {
            // delete mapping
            if (oldValue != null || containsKey(key)) {
                // something to remove
                // 且map中key对应value有值
                // 则删除该key
                remove(key);
                return null;
            } else {
                // nothing to do. Leave things as they were.
                return null;
            }
        } else {
            // add or replace old mapping
            // 若newValue不为null,则插入替换该value值
            put(key, newValue);
            return newValue;
        }
    }

2. computeIfPresent()

  1. 代码例子

    public class demo {
        public static void main(String[] args) {
            Map<String, String> map = new HashMap<>();
            map.put("1", "1");
            map.put("2", "2");
            map.put("3", "3");
            // computeIfPresent():当key存在的时候,都会执行后面方法
            // 1. key 存在才会执行后面方法
            // 2. newValue为null,则remove()
            // 3. newValue不为null,则put(key,newValue)
            map.computeIfPresent("1", (k, v) -> null);
            map.computeIfPresent("2", (k, v) -> k + "---" + v);
            map.computeIfPresent("5", (k, v) -> k);
            System.out.println(map);
    
        }
    }
    

    在这里插入图片描述

  2. 源码

    default V computeIfPresent(K key,
                BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
            Objects.requireNonNull(remappingFunction);
            V oldValue;
            // 相对于compute(),新增一个判断条件
            // 若oldValue不为空才执行Function方法
            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;
            }
        }
    

3. computeIfAbsent()

  1. 代码例子:

    public class demo {
        public static void main(String[] args) {
            Map<String, String> map = new HashMap<>();
            map.put("1", "1");
            map.put("2", "2");
            map.put("3", "3");
            // computeIfAbsent():当key不存在的时候,都才会执行后面方法
            // 因为key不存在,固然没 k,v 因此function并不是(k,v)结构
            // 1. key 不存在才会执行后面方法
            // 2. newValue不为null,则put(key,newValue)
            map.computeIfAbsent("1", e -> "111");
            map.computeIfAbsent("5", e -> e + "-" + e);
            System.out.println(map);
    
        }
    }
    

    在这里插入图片描述

  2. 源码

    default V computeIfAbsent(K key,
                Function<? super K, ? extends V> mappingFunction) {
            Objects.requireNonNull(mappingFunction);
            V v;
            // 若value为null,才执行function方法
            if ((v = get(key)) == null) {
                V newValue;
                if ((newValue = mappingFunction.apply(key)) != null) {
                // 且当返回的newValue不为null,则插入替换原来value值
                    put(key, newValue);
                    return newValue;
                }
            }
    
            return v;
        }
    

4.merge()

  1. 代码例子

    public class demo {
        public static void main(String[] args) {
            Map<String, String> map = new HashMap<>();
            map.put("1", "1");
            map.put("2", "2");
            map.put("3", "3");
            // merge(key,value,function):
            // 1. 当get(key)为null的时候,直接put(key,value)
            // 2. 当key存在的时候,执行function方法,newValue为null,则remove(key),反之 put(key,newValue);
            map.merge("1", "1", (k, v) -> k + "-" + v);
            map.merge("5", "5", (k, v) -> k + "-" + v);
            System.out.println(map);
        }
    }
    

    在这里插入图片描述

  2. 源码

    default V merge(K key, V value,
                BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
            Objects.requireNonNull(remappingFunction);
            Objects.requireNonNull(value);
            V oldValue = get(key);
            // 先判断map中是否有对应的值
            // 有则执行function方法
            // 无则put(key,value)
            V newValue = (oldValue == null) ? value :
                       remappingFunction.apply(oldValue, value);
            if(newValue == null) {
                remove(key);
            } else {
                put(key, newValue);
            }
            return newValue;
        }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值