Map的compute相关方法
· 阅读需 4 分钟
介绍
都是get方法的变种,自带修改值的处理。
方法 | 介绍 |
---|---|
compute | 根据指定的键和计算函数对指定键的值进行修改,通用。 |
computeIfAbsent | get的值为 null 值时,根据函数计算结果赋值给v,适用于设置默认值。 |
computeIfPresent | get的值不为 null 时,对指定键的值进行修改,适用于仅对有值的键进行处理的时候 |
注意
compute
、computeIfPresent
处理的如果是已存在的键,remappingFunction
如果返回null,等于从Map中的删除此键!
compute方法
通用的处理值的方法,无论有无值都执行函数处理值。
方法签名
default V compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction)
key
:要操作的键。remappingFunction
:一个接收键和当前键对应的值作为输入,并返回一个新值的函数。
常例
获取键对应的值(不存在键和值为null获取都是null),执行函数返回新值,替换旧值并返回计算后的值。
Integer compute1 = map.compute("d", (k, v) -> v == null ? 0 : v + 1);
说明
compute 方法的行为取决于指定的键当前是否存在于Map
中:
如果指定的键存在且不为null,则将键和值传递给remappingFunction
函数。将函数计算后的值设置为该键,并且返回该值。
如果指定的键不存在或为null时,则根据remappingFunction
函数的返回值来确定如何处理:
如果返回不为null,将新的键值对添加到Map
中,否则则将该键从Map
中删除。
代码
Map<String,Integer> map = new LinkedHashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
map.put("d", null);
// a存在,按函数计算值,并返回计算结果
Integer compute1 = map.compute("a", (k, v) -> v == null ? 0 : v + 1);
System.out.println("compute1:" + compute1);
// z不存在,按函数计算值,并返回计算结果
Integer compute2 = map.compute("z", (k, v) -> v == null ? 0 : v + 1);
System.out.println("compute2:" + compute2);