对于HashMap,使用compute()还是put()效率更高

For HashMap, is it more efficient to use compute() or put()

我已经尝试四处寻找了一段时间,但我找不到具体的答案,而且仍然无法准确理解 HashMapcompute 方法的作用。

我目前的理解是 compute 将允许您操作该值但不能将其设置为新值(例如垃圾收集器必须清除旧对象的地方) ) 而 put 只会删除旧对象并设置它(就像去 x = new Something)。

如果我对此的理解有误,请告诉我,但不管怎样,compute 方法通常更有效吗?我应该尽可能在 put 上使用它还是只在某些情况下使用它?

如果您想无条件设置新值,请使用put。如果要根据地图中的现有值计算新值,请使用 compute。您可以选择将其更改为新值或将其从地图中删除。

documentation for compute 指出:

The default implementation is equivalent to performing the following steps for this map:

V oldValue = map.get(key);
V newValue = remappingFunction.apply(key, oldValue);
if (newValue != null) {
    map.put(key, newValue);
} else if (oldValue != null || map.containsKey(key)) {
    map.remove(key);
}
return newValue;

比简单的要复杂put:

  1. 它调用 get 来检索当前值。
  2. 它调用提供的重映射函数将其转换为新值。
  3. 它要么调用 put 覆盖旧值,要么调用 remove 删除旧值,具体取决于新值是否为 null。

因为最终调用了putcompute的步骤更多而且更慢。如果 put 满足您的需求——您不关心地图中的内容,您只想将一个键设置为一个值——使用 put.