集合類中新增了一些函數(shù)以支持lambda編程
集合類型 | 方法 |
---|---|
Collection | removeIf() spliterator() stream() parallelStream() forEach() |
List | replaceAll() sort() |
Map | getOrDefault() forEach() replaceAll() putIfAbsent() remove() replace() computeIfAbsent() computeIfPresent() compute() merge() |
removeIf
removeIf(Predicate<? super E> filter)
刪除此集合中滿足給定Predicate的所有元素萍鲸。在迭代期間或由Predicate引發(fā)的錯(cuò)誤或運(yùn)行時(shí)異常將被轉(zhuǎn)發(fā)給調(diào)用方霞揉。
compute
compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
它的默認(rèn)實(shí)現(xiàn)如下桦锄,包含5個(gè)步驟:
①首先對(duì)<key,oldValue>
應(yīng)用remappingFunction
得到 newValue
②如果oldValue
不為空且newValue
也不為空犯眠,那么用newValue
替換oldValue
③如果oldValue
不為空但是newValue
為空灵寺,那么從map中刪掉<key,oldValue>
這個(gè)記錄
④如果oldValue
為空(可能對(duì)于的key
不存在张漂,對(duì)于value
可以為空的map
來說也可能是<key,null>
這種情況)那么插入<key,newValue>
(或用newValue
替換oldValue
)
⑤如果oldValue
為空且newValue
也為空肢预,那就什么也不做冕杠,直接返回null
V oldValue = map.get(key);
V newValue = remappingFunction.apply(key, oldValue); //對(duì)于步驟1
if (oldValue != null ) {
if (newValue != null) //對(duì)應(yīng)步驟2
map.put(key, newValue);
else //對(duì)應(yīng)步驟3
map.remove(key);
} else {
if (newValue != null) //對(duì)應(yīng)步驟4
map.put(key, newValue);
else ////對(duì)應(yīng)步驟5
return null;
}
computeIfAbsent
computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)
它的實(shí)現(xiàn)如下:
if (map.get(key) == null) {
V newValue = mappingFunction.apply(key);
if (newValue != null)
map.put(key, newValue);
}
computeIfPresent
computeIfPresent(K key, BiFunction<? super K,? super V,? extendsV> remappingFunction)
它的實(shí)現(xiàn)如下:
if (map.get(key) != null) {
V oldValue = map.get(key);
V newValue = remappingFunction.apply(key, oldValue);
if (newValue != null)
map.put(key, newValue);
else
map.remove(key);
}
merge
merge(K key, V value, BiFunction<? super V,? super V,? extendsV> remappingFunction)
merge 可用來合并兩個(gè)map,以及當(dāng)兩個(gè)map有相同的k,v時(shí)如何處理
它的默認(rèn)實(shí)現(xiàn)如下
V oldValue = map.get(key);
V newValue = (oldValue == null) ? value :
remappingFunction.apply(oldValue, value);
if (newValue == null)
map.remove(key);
else
map.put(key, newValue);
replaceAll
replaceAll(BiFunction<? super K,? super V,? extends V> function)
應(yīng)用BiFunction替換所有的value值微姊,直到處理完所有entry或函數(shù)拋出異常為止。函數(shù)拋出的異常被轉(zhuǎn)發(fā)給調(diào)用者
demo
使用replaceAll
將map
的<k,v>
替換為<k,k_v>
的形式
Map<String, String> map = new HashMap<>();
map.put("k1", "v1");
map.put("k2", "v2");
map.put("k3", "v3");
map.put("k4", "v4");
map.replaceAll((k, v) -> String.join("_", k, v));
System.out.println(map);
output
{k1=k1_v1, k2=k2_v2, k3=k3_v3, k4=k4_v4}