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方法怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!

网页标题:jdk1.8中map的compute,computeIfAbsent,computeIfPresent方法怎么用
URL标题:https://www.cdcxhl.com/article20/igcjjo.html

成都网站建设公司_创新互联,为您提供品牌网站设计网站收录关键词优化企业网站制作企业建站移动网站建设

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

营销型网站建设