似乎同时创建了合并和计算Map方法都是为了减少放置时的if(“〜键存在于此〜”)。
我的问题是:当我一无所知时,添加一个映射[key,value]对:映射中既不存在也不存在它,但是具有value或value == null或key == null的映射。
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是从Bifunction移到parameter吗?
有什么更好用的?是否有任何合并,计算表明键/值存在?
它们的用例之间的本质区别是什么?
最佳答案
Map#compute(K, BiFunction)
的文档说:
Attempts to compute a mapping for the specified key and its current mapped value (or
null
if there is no current mapping). For example, to either create or append aString
msg
to a value mapping:map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))
(Method
merge()
is often simpler to use for such purposes.)If the remapping function returns
null
, the mapping is removed (or remains absent if initially absent). If the remapping function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.The remapping function should not modify this map during computation.
并且
Map#merge(K, V, BiFunction)
的文档说:If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is
null
. This method may be of use when combining multiple mapped values for a key. For example, to either create or append aString
msg
to a value mapping:map.merge(key, msg, String::concat)
If the remapping function returns
null
, the mapping is removed. If the remapping function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.The remapping function should not modify this map during computation.
重要的区别是:
compute(K, BiFunction<? super K, ? super V, ? extends V>)
:BiFunction
。 BiFunction
接受给定的键和当前值(如果有)作为参数,并返回一个新值。 merge(K, V, BiFunction<? super V, ? super V, ? extends V>)
:BiFunction
。 BiFunction
接受当前值和给定值作为参数并返回新值。与compute
不同,没有为BiFunction
提供 key 。 关于collections - Java 8 Map合并VS计算,有本质区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58146053/