putIfAbsent、computeIfAbsent、computeIfPresent

putIfAbsent

判断是否存在,不存在则设置

hashmap.putIfAbsent(K key, V value)

例子如下:

 public static void main(String[] args) {
        //hashmap.putIfAbsent(K key, V value)
        HashMap hashMap = Maps.newHashMap();
        hashMap.put("aa","one");

        hashMap.putIfAbsent("bb","two");
        hashMap.values().stream().forEach(e->{
            System.out.println(e);
                }
        );
        hashMap.putIfAbsent("bb","three");
        hashMap.values().stream().forEach(e->{
            System.out.println(e);
        });

    }

,输出如下:

computeIfAbsent

判断执行的key是否存在,存在则还回对应的value,如果key不存在,则设置进去。

hashmap.computeIfAbsent(K key, Function remappingFunction)

如下例子:

HashMap<String,Integer> hashMap = Maps.newHashMap();
        hashMap.put("one",280);
        hashMap.put("two",320);
        hashMap.put("three",410);
        Integer aa = hashMap.computeIfAbsent("one",key->290);
        System.out.println("aa=====:"+aa);
        System.out.println(hashMap);

输出如下:

computeIfPresent

对hashmap里面的key做判断,存在则对里面的value做重新计算,不存在则还回null

对hashmap里面指定的key的值做重新计算。

hashmap.computeIfPresent(K key, BiFunction remappingFunction)

例子如下:

  HashMap<String,Integer> hashMap = Maps.newHashMap();
        hashMap.put("one",280);
        hashMap.put("two",320);
        hashMap.put("three",410);
        Integer aa = hashMap.computeIfPresent("four",(key,value)->290);
        System.out.println("aa=====:"+aa);
        System.out.println(hashMap);

还回

存在则重新计算如下:还回的是计算过的值

  HashMap<String,Integer> hashMap = Maps.newHashMap();
        hashMap.put("one",280);
        hashMap.put("two",320);
        hashMap.put("three",410);
        Integer aa = hashMap.computeIfPresent("one",(key,value)->290);
        System.out.println("aa=====:"+aa);
        System.out.println(hashMap);

结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值