jdk8 Map接口 putIfAbsent 和 computeIfAbsent的区别?

computeIfAbsent 和 putIfAbsent 区别有以下三点:

  1. 当key 存在的时候,如果value获取比较昂贵的话,putifAbsent 就白白浪费时间在获取这个昂贵的value上。
  2. key 不存在的时候,putIfAbsent 返回null, 小心空指针,而computeIfAbsent 返回计算后的值。
  3. 当key 不存在的时候,putifAbsent 允许put null 进去,而 computeIfAbsent 不能,之后进行containsKey查询是有区别的。

具体用法如下:

  1. putIfAbsent
  • 传统的put方法,只要key存在,value值就会被覆盖,注意 put方法返回的是put之前的值,如果无put之前的值返回nul
  • putIfAbsent方法,只有在key不存在或者key为null的时候,value值才会被覆盖
   default V putIfAbsent(K key, V value) {
        V v = get(key);
        if (v == null) {
            v = put(key, value);
        }

        return v;
    }

使用场景:如果我们要变更某个key的值,我们又不知道key是否存在的情况下,而又不希望增加key的情况使用。

  1. computeIfAbsent

在返回值上不一样,vaue值不存在的时候,返回的是新的value值,同时可以通过自定义一些条件进行过滤。
value 存在的时候返回的是旧值。

public class MapTest3 {
    static  List<People> peopleList = Arrays.asList(
            new People("张三",2),
            new People("李四",15),
            new People("tom",8),
            new People("jack",10),
            new People("lili",8),
            new People("lucy",2));

    public static void main(String[] args) {
        testComputeIfAbsent();
    }

    private static  void testComputeIfAbsent(){
        //声明接收结果的 map
        Map<Integer, List<People>> resultMap = new HashMap<Integer, List<People>>();
        //按照年龄分组
        for (People people : peopleList) {
            //putIfAbsent方法,只有在key不存在或者key为null的时候,value值才会被覆盖
            // 返回的旧值,如果key不存在则返回null
            List<People> s = resultMap.putIfAbsent(people.getAge(), new ArrayList<People>());
            if(s==null) {//此时重新获取一次,就能到初始化好的List数组
                s = resultMap.putIfAbsent(people.getAge(), new ArrayList<People>());
            }
            s.add(people);
        }
        System.out.println(resultMap);

        resultMap = new HashMap<Integer, List<People>>();
        //对5岁以上的人进行分组
        for (People people : peopleList) {
            //如果value值不存在,返回的是新的value值
            //如果value存在,则返回的是旧值
            List<People> s = resultMap.computeIfAbsent(people.getAge(), k ->{
                if(k>5) {
                    return new ArrayList<People>();
                }
                return null;
            });

            if(s!=null) {
                s.add(people);
            }
        }
        System.out.println(resultMap);
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半夏_2021

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值