优势:

1.代码简介度高

2.非常容易进行并行运算

3.符合未来的编程趋势

4.结合hashMap的computelfAbsent方法,递归算力高,且java有针对递归的专门优化

劣势:

1.如果不使用并行运算,可能算力不如普通的for循环效率高(并行运算有时候需要预热才能体现出算力优势)

2.不容易调试,因为代码过于简洁,所以不能很直观的定位bug位置,且如果同事对lambda表达式不够熟悉,可读性不会很高

3.在lambda表达式中类型转换很不方便

4.在lambda表达式中引用外部常量需要加final修饰符,且引用的常量必须为不可变类型,也就是说什么i++,循环赋值等都是不允许的

外部拓展

关于hashMap的computeIfAbsent()和computeIfPresent()拓展—JDK1.8新特性

computeIfAbsent()源码

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;
}

computeIfAbsent()源码翻译

如果get(key)为null,那么就创建一个value值,这个value值就是lambda表达式的返回值,并且这个返回值不为null,才会将这个这个值存到map对应的key中。— 不为空就更新,为空就不更新直接返回

简单来说,就是:map中key值存在就不更新,不存在就更新

方法总结:

只有在当前 Map 中 key 对应的值不存在或为 null 时
才调用 mappingFunction
并在 mappingFunction 执行结果非 null 时
将结果跟 key 关联.
mappingFunction 为空时 将抛出空指针异常

computeIfPresent()源码

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;
}
}

computeIfPresent()源码翻译

当get(key)值存在时,并且新值不为空,就会更新。否则就返回null

结合使用

先用computeIfAbsent()方法,保证一定可以获取到get(key)
再用computeIfPresent() 方法,保证一定对get(key)更新。