jdk1.8中map中compute,computeIfAbsent,computeIfPresent方法介绍

2 篇文章 0 订阅
1 篇文章 0 订阅

 

1.compute

compute:V compute(K key, BiFunction < ? super K, ? super V, ? extends V> remappingFunction)

compute的方法,指定的key在map中的值进行操作 不管存不存在,操作完成后保存到map中

        HashMap<String,Integer> map = new HashMap<>();
        map.put("1",1);
        map.put("2",2);
        map.put("3",3);
        Integer integer = map.compute("3", (k,v) -> v+1 );
        //key不管存在不在都会执行后面的函数,并保存到map中
        Integer integer1 = map.compute("4", (k,v) -> {
            if (v==null)return 0;
            return v+1;
        } );
        System.out.println(integer);
        System.out.println(integer1);
        System.out.println(map.toString());

打印结果
4
0
{1=1, 2=2, 3=4, 4=0}

2.computeIfAbsent

computeIfAbsent(K key, Function《? super K, ? extends V> mappingFunction)

computeIfAbsent的方法有两个参数 第一个是所选map的key,第二个是需要做的操作。这个方法当key值不存在时才起作用。

当key存在返回当前value值,不存在执行函数并保存到map中

    HashMap<String,Integer> map = new HashMap<>();
    map.put("1",1);
    map.put("2",2);
    map.put("3",3);
    Integer integer = map.computeIfAbsent("3", key -> new Integer(4));//key存在返回value
    Integer integer1 = map.computeIfAbsent("4", key -> new Integer(4));//key不存在执行函数存入
    System.out.println(integer);
    System.out.println(integer1);
    System.out.println(map.toString());


打印结果
3
4
{1=1, 2=2, 3=3, 4=4}

3.computeIfPresent

computeIfPresent:V computeIfPresent(K key, BiFunction < ? super K, ? super V, ? extends V> remappingFunction)

computeIfPresent 的方法,对 指定的 在map中已经存在的key的value进行操作。只对已经存在key的进行操作,其他不操作

        HashMap<String,Integer> map = new HashMap<>();
        map.put("1",1);
        map.put("2",2);
        map.put("3",3);
        //只对map中存在的key对应的value进行操作
        Integer integer = map.computeIfPresent("3", (k,v) -> v+1 );
        Integer integer1 = map.computeIfPresent("4", (k,v) -> {
            if (v==null)return 0;
            return v+1;
        } );
        System.out.println(integer);
        System.out.println(integer1);
        System.out.println(map.toString());


打印结果
4
null
{1=1, 2=2, 3=4}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值