collections - Java 8 Map合并VS计算,有本质区别吗?

标签 collections java-8

似乎同时创建了合并和计算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 a String 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 a String 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/

    相关文章:

    java - 使用 java 8 lambda 将映射转换为字符串

    java - 从 List<Foo> 到 Map<String, List<Foo>> : looking for a better implementation

    java - 如何在没有并发修改异常的情况下在for循环内将元素添加到java中的arraylist

    c# - 有没有类似 List<String, Int32, Int32> (多维通用列表)的东西

    java - 这个 Lambda 表达式的解释

    java - 使用 Java 8 更改列表中元素的所有位置

    symfony - Doctrine - Criteria - expressions - 包含(多对多)

    Java:打印不带方括号的链表?

    c# - WPF Datagrid 分组和排序

    java - Stream Java 中的私有(private)排序规则