java - 为什么 Java 在 Map 中没有 putIfAbsent(key, supplier) 方法?

标签 java collections map

我最近发现自己想要 java.util.Map 中的一个 putIfAbsent(...) 版本,您可以为其提供某种工厂方法,以实例化一个对象(如果它不存在)。这会简化很多代码。

这是我修改后的界面:

import java.util.Map;
import java.util.function.Supplier;

/**
 * Extension of the Map Interface for a different approach on having putIfAbsent
 * 
 * @author Martin Braun
 */
public interface SupplierMap<K, V> extends Map<K, V> {

    public default V putIfAbsent(K key, Supplier<V> supplier) {
        V value = this.get(key);
        if(value == null) {
            this.put(key, value = supplier.get());
        }
        return value;
    }

}

现在我的问题是: 是否有另一种(更简单的)方法可以做到这一点,或者我只是忽略了 Java API 中的某些内容?

最佳答案

不是 computeIfAbsent 你想要什么?

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.

实现是这样的:

if (map.get(key) == null) {
    V newValue = mappingFunction.apply(key);
    if (newValue != null) {
         map.put(key, newValue);
    }
}

所以它不完全是 Supplier<V>您已发布但接近的签名。在映射函数中将键作为参数绝对有意义。

关于java - 为什么 Java 在 Map 中没有 putIfAbsent(key, supplier) 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27127392/

相关文章:

java - 为什么这是 SQL 文件或流的分隔符?

java - 删除mongodb java中的子节点

java-如何将 ArrayList<ArrayList<String>> 转换为 String[]][]

oop - Map 和 SortedMap - 冗余方法声明

c# - 创建将类型 T 作为键映射到类型 T 实例的字典

java - 针对单个键在映射中存储多个值

java - 使用 Volley 和 Gson : Parse item and items list

java - 什么是允许 Collections.sort 的线程安全 List 实现

java - 我应该什么时候使用 ConcurrentSkipListMap?

具有交互和映射的 Haskell IO