JDK1.8 HashMap中computeIfAbsent、computeIfPresent、compute方法的区别和例子

JDK1.8 HashMap中computeIfAbsent、computeIfPresent、compute方法的区别和例子

1)computeIfAbsent

		1、它当键不存在时或者键存在但是值为null时,后面的Function类才会起到作用。
		HashMap<Integer,Integer> hashMap = new HashMap<>(10,0.5f);
        hashMap.put(3,null);
        Integer in = hashMap.computeIfAbsent(3,(k)->10);
        System.out.println(in);
        System.out.println(hashMap.get(3));
        注意:这里虽然key是存在的,但是由于值为null,还是会使用
        Function函数的apply方法,运行结果如下:

在这里插入图片描述
还需要注意的是,如果key不存在,并且Function类实现的apply方法返回值不为null,就会将这个key作为新节点增加进去,value为apply返回值

HashMap<Integer,Integer> hashMap = new HashMap<>(10,0.5f);
        hashMap.put(3,null);
        System.out.println("执行computeIfAbsent方法之前:"+hashMap.get(new Integer(4)));
        Integer in = hashMap.computeIfAbsent(4,(k)->20);
        System.out.println("执行computeIfAbsent方法之后:"+hashMap.get(new Integer(4)));
        结果如下图:

在这里插入图片描述

2)computeIfPresent

		1、它只有当键存在的时候,后面BiFunction类才会起到作用,
		会将BiFunction类的apply方法的返回值覆盖键的当前值,
		但是如果返回值为null,就会进行节点的删除
HashMap<Integer,Integer> hashMap = new HashMap<>(10,0.5f);
        hashMap.put(3,10);
        System.out.println("执行computeIfAbsent方法之前:"+hashMap.get(new Integer(3)));
        Integer in = hashMap.computeIfPresent(3,(k,v)->null);
        System.out.println("执行computeIfAbsent方法之后:"+hashMap.get(new Integer(3)));
        结果如下图:

在这里插入图片描述

3)compute

		1、键存不存在后面的BiFunction类都会起到作用
		2、但是相对的,会分两种情况进行删除或者新增节点
			1)如果key存在,并且BiFunction的apply方法返回值
				不为null,就会进行值的更新,否则就会进行节点删除
			2)如果key不存在,并且BiFunction的apply方法返回值
				不为null,就会进行节点的新增
HashMap<Integer,Integer> hashMap = new HashMap<>(10,0.5f);
        hashMap.put(3,10);
        //测试key存在,并且BiFunction的apply方法返回值为null的情况
        System.out.println("使用compute之前:"+hashMap.get(new Integer(3)));
        Integer in = hashMap.compute(3,(k,v)->300);
        System.out.println("使用compute之后:"+hashMap.get(new Integer(3)));
        //测试key存在,并且BiFunction的apply方法返回值为null的情况
        System.out.println("使用compute之前:"+hashMap.get(new Integer(3)));
        in = hashMap.compute(3,(k,v)->null);
        System.out.println("使用compute之后:"+hashMap.get(new Integer(3)));
        结果如下:

在这里插入图片描述

HashMap<Integer,Integer> hashMap = new HashMap<>(10,0.5f);
        hashMap.put(3,10);
        //测试key不存在
        System.out.println("使用compute之前:"+hashMap.get(new Integer(5)));
        Integer in = hashMap.compute(5,(k,v)->300);
        System.out.println("使用compute之后:"+hashMap.get(new Integer(5)));
        结果如下图:

在这里插入图片描述

有错误欢迎指出!!!

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值