java 8中map中compute,computeIfAbsent,computeIfPresent方法介绍

compute(计算)

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

指定的key值在map中的value值进行操作, 如果key存在,则可操作value值; 如果key不存在,操作完成后key,value都保存到map中

    Map<String,Integer> map= Maps.newHashMap();
        map.put("1",1);
        map.put("2",2);
        map.put("3",3);
        
        Integer integer = map.compute("3", (k,v) -> v+1 );
        System.out.println(map);
        Integer integer1 = map.compute("4", (k,v) -> v=9);
        System.out.println(map);
        
    输出:   
    {1=1, 2=2, 3=4}
    {1=1, 2=2, 3=4, 4=9}


computeIfAbsent(不存在时计算)

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

第一个是所选map的key,第二个是需要做的操作。这个方法当key值不存在时才起作用。当key存在返回当前value值,不存在执行函数并保存到map中.

   Map<String, Integer> map = Maps.newHashMap();
        map.put("1", 1);
        map.put("2", 2);
        map.put("3", 3);
        //key值存在,则不做操作
        map.computeIfAbsent("1", key -> 90);
        System.out.println(map);
        //key 值不存在,则做操作
        map.computeIfAbsent("4", key -> 90);
        System.out.println(map);
        
    输出:
    {1=1, 2=2, 3=3}
    {1=1, 2=2, 3=3, 4=90}

computeIfPresent(存在时计算)

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

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

     Map<String, Integer> map = Maps.newHashMap();
        map.put("1", 1);
        map.put("2", 2);
        map.put("3", 3);
        //key值存在则计算
        map.computeIfPresent("3", (key, value) -> value = 10);
        System.out.println(map);
        //key值不存在,则不做操作
        map.computeIfPresent("4", (key, value) -> 90);
        System.out.println(map);
    输出:
    {1=1, 2=2, 3=10}
    {1=1, 2=2, 3=10}

转载于:https://my.oschina.net/u/563488/blog/3012931

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值