似乎合并和计算Map方法都是为了减少if("~key存在于此~“)而创建的。我的问题是:添加到映射一个键,值对时,我不知道:在map中既不存在键,也不存在它,但是它没有值,也没有值==空或键==空。
words.forEach(word ->
map.compute(word, (w, prev) -> prev != null ? prev + 1 : 1)
);
words.forEach(word ->
map.merge(word, 1, (prev, one) -> prev + one)
);
唯一的区别1是从双函数移动到参数吗?还有什么更好用的呢?是否有任何合并、计算提示键/val存在?它们在用例上有什么本质的区别?
发布于 2019-09-28 12:53:07
Map#compute(K, BiFunction)
的文档显示:
试图计算指定键及其当前映射值的映射(如果没有当前映射,则为
null
)。例如,要在值映射中创建或追加String
msg
:
map.compute(key,(k,v) -> (v == null)?味精:v.concat(味精)
(方法merge()
)
如果重映射函数返回null
,映射将被移除(如果最初不存在,则仍然不存在)。如果重映射函数本身抛出一个(未检查的)异常,则重新抛出异常,并且当前映射保持不变。
在计算期间,重映射函数不应修改此映射。
Map#merge(K, V, BiFunction)
的文档显示:
如果指定的键尚未与值相关联或与null关联,则将其与给定的非空值关联。否则,用给定的重映射函数的结果替换关联的值,或者如果结果是
null
,则删除。当组合一个键的多个映射值时,此方法可能有用。例如,要在值映射中创建或追加String
msg
:
map.merge(key,msg,String::concat)
如果重映射函数返回null
,则将删除映射。如果重映射函数本身抛出一个(未检查的)异常,则重新抛出异常,并且当前映射保持不变。
在计算期间,重映射函数不应修改此映射。
重要的区别是:
compute(K, BiFunction<? super K, ? super V, ? extends V>)
的
- The `BiFunction` is _always_ invoked.
- The `BiFunction` accepts the given key and the current value, if any, as arguments and returns a new value.
- Meant for taking the key and current value (if any), performing an arbitrary computation, and returning the result. The computation may be a reduction operation (i.e. merge) but it doesn't have to be.
merge(K, V, BiFunction<? super V, ? super V, ? extends V>)
的
- The `BiFunction` is invoked _only if the given key is already associated with a non-null value_.
- The `BiFunction` accepts the current value and the given value as arguments and returns a new value. Unlike with `compute`, the `BiFunction` is not given the key.
- Meant for taking two values and reducing them into a single value.
发布于 2020-04-04 15:08:25
如果映射函数(在您的情况下)只依赖于当前映射的值,那么您可以使用这两种方法。但我更希望:
如果可以保证给定键的值存在,则为
compute
。在这种情况下,如果可能不存在给定键的值,则合并方法获取的额外值参数不是needed.merge
。在这种情况下,合并的优点是null
不必由映射函数处理。https://stackoverflow.com/questions/58146053
复制相似问题