是否覆盖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);//空指针
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。