我最近发现自己想要 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/