java lambda

集合类对lambda的扩展

2019-01-31  本文已影响0人  spraysss

集合类中新增了一些函数以支持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引发的错误或运行时异常将被转发给调用方。

compute

compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
它的默认实现如下,包含5个步骤:

①首先对<key,oldValue> 应用remappingFunction得到 newValue
②如果oldValue不为空且newValue 也不为空,那么用newValue替换oldValue
③如果oldValue不为空但是newValue为空,那么从map中删掉<key,oldValue> 这个记录
④如果oldValue为空(可能对于的key不存在,对于value可以为空的map来说也可能是<key,null>这种情况)那么插入<key,newValue>(或用newValue替换oldValue)
⑤如果oldValue为空且newValue也为空,那就什么也不做,直接返回null

 
 V oldValue = map.get(key);
 V newValue = remappingFunction.apply(key, oldValue); //对于步骤1
 if (oldValue != null ) {
    if (newValue != null) //对应步骤2
       map.put(key, newValue);
    else  //对应步骤3
       map.remove(key);
 } else {
    if (newValue != null)  //对应步骤4
       map.put(key, newValue);
    else ////对应步骤5
       return null;
 }

computeIfAbsent

computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)

它的实现如下:

 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)
它的实现如下:

 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 可用来合并两个map,以及当两个map有相同的k,v时如何处理

它的默认实现如下

 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)
应用BiFunction替换所有的value值,直到处理完所有entry或函数抛出异常为止。函数抛出的异常被转发给调用者

demo

使用replaceAllmap<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}
上一篇 下一篇

猜你喜欢

热点阅读