pubIfAbsent 源碼:
/**
* 入參key、value。
* 如果獲取到key的值爲null或不存在,則對key進行覆蓋添加。並返回新的value值。
* 如果對應的key的值是存在的且不等於null,對key,value進行put,返回put的結果(value)。
*/
default V putIfAbsent(K key, V value) {
V v = get(key);
if (v == null) {
v = put(key, value);
}
return v;
}
computeIfAbsent 源碼:
/**
* 入參key,Function的對象(可以使用lambda表達式,暫時不清楚其實現)
* Function對象使用lambda表達式 k -> v 入參是key, v是返回值
* mappingFunction.apply()實現了部分業務並返回value
*
* 如果key獲取到的value是null或不存在,獲取到value,並對key,value進行put。並返回put結果(value)
* 如果value值已經存在,且不等於null,返回value值。
*
*/
default V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
V v;
if ((v = get(key)) == null) {
V newValue;
if ((newValue = mappingFunction.apply(key)) != null) {
put(key, newValue);
return newValue;
}
}
return v;
}
computeIfPresent 源碼:
/**
* 入參key,BiFunction的對象(可以使用lambda表達式,暫時不清楚其實現)
* BiFunction對象使用lambda表達式 (k, v) -> v 入參是key, value 返回值是value的同類型的結果
* remappingFunction.apply()實現了其中oldValue到newValue的轉換
*
* 如果不存在key或者key的值是null,返回null
* 如果newValue是null,則移除key,並返回null
* 否則對key,newValue進行put,返回newValue
*
*/
default V computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue;
if ((oldValue = get(key)) != null) {
V newValue = remappingFunction.apply(key, oldValue);
if (newValue != null) {
put(key, newValue);
return newValue;
} else {
remove(key);
return null;
}
} else {
return null;
}
}