是否笼罩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);//空指针
}
发表回复