jdk1.8中map的compute,computeIfAbsent,computeIfPresent方法怎么用

这篇文章主要为大家展示了“jdk1.8中map的compute,computeIfAbsent,computeIfPresent方法怎么用”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“jdk1.8中map的compute,computeIfAbsent,computeIfPresent方法怎么用”这篇文章吧。

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}

以上是“jdk1.8中map的compute,computeIfAbsent,computeIfPresent方法怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!