Map中ComputeIfAbsent与computeIfPresent区别
1、ComputeIfAbsent
(1)、如果里面有值,就返回;
(2)、如果里面没有值,就使用后面的函数计算;
(3)、如果后面计算的函数为空,返回空,不将null值放入map;
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
map.put("key", "1");
String value = map.computeIfAbsent("key", k -> "12" + 1);
System.out.println("value = " + value);
System.out.println("map = " + map.toString());
2、ComputeIfPresent
(1)如果key存在,就将重新计算的值,放到key中,并返回新的值;
(2)如果不存在,就返回null,不做处理;
HashMap<String, String> map = new HashMap<>();
map.put("key", "1");
String newValue = map.computeIfPresent("key", (k,v) -> k + v);
System.out.println("newValue = " + newValue);
System.out.println("map = " + map.toString());
String newValueNull = map.computeIfPresent("key1", (k,v) -> k + v);
System.out.println("newValueNull = " + newValueNull);