关于java:Map中put与computecomputeIfAbsent与putIfAbsent区别

7次阅读

共计 1704 个字符,预计需要花费 5 分钟才能阅读完成。

是否笼罩 value 返回值 是否容许 null
put 笼罩前
compute 笼罩后
putIfAbsent 笼罩前
computeIfAbsent 笼罩后

阐明:

1. put

put 返回旧值,如果没有则返回 null

2. compute(相当于 put, 只不过返回的是新值)


compute 返回新值, 当 key 不存在时,执行 value 计算方法,计算 value

3. putIfAbsent

putIfAbsent 返回旧值,如果没有则返回 null
先计算 value,再判断 key 是否存在
当 Key 存在的时候,如果 Value 获取比拟低廉的话,putIfAbsent 就白白浪费工夫在获取这个低廉的 Value 上。

4. computeIfAbsent

computeIfAbsent: 存在时返回存在的值,不存在时返回新值
参数为:key,value 计算方法
先判断 key 是否存在,再执行 value 计算方法

总结:

1. put 与 compute:

 雷同:不管 key 是否存在,强制用 value 笼罩进去。区别:put 返回旧 value 或 null,compute 返回新的 value

2. putIfAbsent 与 computeIfAbsent:

 雷同:key 存在,则不操作,key 不存在,则赋值一对新的(key,value)区别:putIfAbsent 返回旧 value 或 null,computeIfAbsent 返回新的 value

      putIfAbsent 适宜增加具备指定值的元素,而 computeIfAbsent 适宜增加具备应用键计算的值的元素,key 可参加计算。map.putIfAbsent("Key3", "Value3");
  map.computeIfAbsent("Key3", e->"Value".concat(e.substring(3,4))); 
  

测试代码及后果:

public void testMap() {Map<String, String> map = new HashMap<>();
    map.put("a", "A");
    map.put("b", "B");
    String val = map.compute("b", (k, v) -> "B2"); // 返回 B2 
    System.out.println(val);
    String v1 = map.compute("c", (k, v) -> "C"); // 返回 C 
    System.out.println(v1);
    System.out.println(map);
}
public void testMap2() {Map<String, String> map = new HashMap<>();
    map.put("a","A");
    map.put("b","B");
    String v = map.putIfAbsent("b","B2");  // 返回 B 
    System.out.println(v);
    String v1 = map.putIfAbsent("c","C");  // 返回 null 
    System.out.println(v1);
    System.out.println(map);
}
public void testMap3() {Map<String, String> map = new HashMap<>();
    map.put("a","A");
    map.put("b","B");
    String v = map.computeIfAbsent("b",k->"B2");  // 返回 B
    System.out.println(v);
    String v1 = map.computeIfAbsent("c",k->"C"); // 返回 C 
    System.out.println(v1);
    System.out.println(map);
}
public void testMap4() {Map<String, String> map = new HashMap<>();
    map.put("a","A");
    map.put("b","B");
    map.put("c", null);// 容许
    map.putIfAbsent("d", null);// 容许
    map.compute("e", null);// 空指针
    map.computeIfAbsent("f", null);// 空指针
}
正文完
 0