前言
java8中對(duì)map的使用新增了一些十分有用的方法,以下列舉部分常用methed()
常用方法解析
1、compute()
參數(shù)格式:
compute(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)
簡(jiǎn)要說明:
不在乎當(dāng)前item的舊值,直接以remappingFunction()
結(jié)果的新值為準(zhǔn),如果新值為空則移除當(dāng)前item.
源碼分析:
default V compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue = get(key);
V newValue = remappingFunction.apply(key, oldValue);
if (newValue == null) {
// delete mapping
if (oldValue != null || containsKey(key)) {
// something to remove
remove(key);
return null;
} else {
// nothing to do. Leave things as they were.
return null;
}
} else {
// add or replace old mapping
put(key, newValue);
return newValue;
}
使用格式:
testMap.compute("key1", (v1, v2) -> v2);
使用場(chǎng)景:
put()
方法的增強(qiáng)使用
2锥腻、computeIfPresent()
參數(shù)格式:
computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
簡(jiǎn)要說明:
計(jì)算item方法, 入?yún)閕tem的key、remappingFunction
如果原來(lái)的key有值,且不為null,那么將remappingFunction中的新值給key,新值如果為空,移除當(dāng)前key的item
如果原來(lái)key沒值,直接給null
源碼分析:
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;
}
使用格式:
testMap.computeIfPresent("key1", (v1, v2) -> "test");
使用場(chǎng)景:
put()
方法的增強(qiáng)使用
3瓮孙、computeIfAbsent()
參數(shù)格式: computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
簡(jiǎn)要說明:
計(jì)算item方法,入?yún)閕tem的key、remappingFunction
如果當(dāng)前key舊值不為空,那么以舊值為準(zhǔn)
如果當(dāng)前key舊值為空绍赛,以function結(jié)果新值為準(zhǔn),新值為空則remove當(dāng)前item
源碼分析:
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;
}
使用格式:
tempEntityRouteMap.computeIfAbsent(entityType, k -> TreeRangeMap.create());
使用場(chǎng)景:
put()方法的增強(qiáng)使用
未完待續(xù)......