有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我最近发现自己想要一个版本的putIfAbsent(…)在java中。util。映射,您可以向其提供某种工厂方法,以实例化尚未存在的对象。这将简化许多代码

这是我修改过的界面:

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;
    }

}

现在我的问题是: 还有其他(更简单的)方法吗?或者我只是忽略了JavaAPI中的一些东西


共 (2) 个答案

  1. # 1 楼答案

    ComputeFabSent不是对putIfAbsent的1:1替换,因为返回值的约束不匹配。创建新条目时,putIfAbsent返回nullcomputeIfAbsent始终返回指定的值

    上面建议的默认实现是调用get,然后调用put,但它需要在映射中进行两次查找,这破坏了性能就地替换的想法

  2. # 2 楼答案

    你不是想要什么吗

    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>签名,而是接近于此。在映射函数中使用key作为参数显然是有意义的