zoukankan      html  css  js  c++  java
  • JAVA8 Map新方法:compute,computeIfAbsent,putIfAbsent与put的区别

    不管存不存在key,都设值:
    1. put
    put返回旧值,如果没有则返回null

    @Test
    public void testMap() {
    Map<String, String> map = new HashMap<>();
    map.put("a","A");
    map.put("b","B");
    String v = map.put("b","v"); // 输出 B
    System.out.println(v);
    String v1 = map.put("c","v");
    System.out.println(v1); // 输出:NULL
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    2. compute(相当于put,只不过返回的是新值)
    compute:返回新值
    当key不存在时,执行value计算方法,计算value


    @Test
    public void testMap() {
    Map<String, String> map = new HashMap<>();
    map.put("a", "A");
    map.put("b", "B");
    String val = map.compute("b", (k, v) -> "v"); // 输出 v
    System.out.println(val);
    String v1 = map.compute("c", (k, v) -> "v"); // 输出 v
    System.out.println(v1);
    }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    以下几个方法,如果不存在,再put:
    1. putIfAbsent
    putIfAbsent返回旧值,如果没有则返回null
    先计算value,再判断key是否存在

    @Test
    public void testMap() {
    Map<String, String> map = new HashMap<>();
    map.put("a","A");
    map.put("b","B");
    String v = map.putIfAbsent("b","v"); // 输出 B
    System.out.println(v);
    String v1 = map.putIfAbsent("c","v"); // 输出 null
    System.out.println(v1);
    }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    2. computeIfAbsent
    computeIfAbsent:存在时返回存在的值,不存在时返回新值
    参数为:key,value计算方法
    当key不存在时,执行value计算方法,计算value

    @Test
    public void testMap() {
    Map<String, String> map = new HashMap<>();
    map.put("a","A");
    map.put("b","B");
    String v = map.computeIfAbsent("b",k->"v"); // 输出 B
    System.out.println(v);
    String v1 = map.computeIfAbsent("c",k->"v"); // 输出 v
    System.out.println(v1);
    }

    ————————————————
    版权声明:本文为CSDN博主「衣冠の禽兽」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/wang_8101/article/details/82191146

  • 相关阅读:
    6个laravel常用目录路径函数
    Laravel上传产品图片Uploading img
    Laravel删除产品-CRUD之delete(destroy)
    Laravel编辑产品-CRUD之edit和update
    Laravel展示产品-CRUD之show
    Laravel创建产品-CRUD之Create and Store
    内存泄露从入门到精通三部曲之排查方法篇
    P问题、NP问题、NPC问题、NP难问题的概念
    二维码的生成细节和原理
    一分钟认识GitHub
  • 原文地址:https://www.cnblogs.com/aspirant/p/14552024.html
Copyright © 2011-2022 走看看