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

  • 相关阅读:
    Hadoop命令大全
    Cube中时间维度
    无法锁定管理目录(/var/lib/dpkg/),是否有其他进程正占用它?
    IE6、IE7、IE8、FF对空标签块状元素解释的不同点
    SSIS导出平面文件数据带_x003C_none_x003E的问题
    用DB2 Runtime Client实现Apache Derby 数据库ODBC编程
    区块链技术探索
    JS原型对象
    this关键字
    消息认证码
  • 原文地址:https://www.cnblogs.com/aspirant/p/14552024.html
Copyright © 2011-2022 走看看