Map的computeIfAbsent和putIfAbsent都是判断第一个参数Object k 在map.keyset中是否存在,不存在则将k同后面的Object value一同保存到Map中。
- 参数不一样。
/** <pre> {@code
if (map.get(key) == null) {
V newValue = mappingFunction.apply(key);
if (newValue != null)
map.put(key, newValue);
}
}</pre>
**/
default V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction
default V putIfAbsent(K key, V value)
/**
V v = get(key);
if (v == null) {
v = put(key, value);
}
return v;
**/
- putIfAbsent 不管怎样key是否存在。当Key存在的时候,如果Value获取比较昂贵的话,putIfAbsent就白白浪费时间在获取这个昂贵的Value上。
- Key不存在的时候,putIfAbsent可以put null value,小心空指针;而computeIfAbsent返回计算后的值,如果为null则不进行put操作
- ConcurrentHashMap不允许put null 进去(key和velue都不可以为null)
官方文档截图: