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

  • 相关阅读:
    APP调用微信支付
    怎么在腾讯云上部署项目
    Jfinal中使用redis
    Jfinal框架中使用WebSocket
    一道sql面试题
    git本地仓库上传到git远程仓库的指令
    怎么启动postsqlgres
    SpringMVC用List接收请求参数
    转发 电商面试题100问
    转--MyBatis-Plus代码自动生成工具
  • 原文地址:https://www.cnblogs.com/aspirant/p/14552024.html
Copyright © 2011-2022 走看看