簡體   English   中英

為什么Java在Map中沒有putIfAbsent(key,supplier)方法?

[英]Why doesn't Java have a putIfAbsent(key, supplier) method in Map?

我最近發現自己想在java.util.Map中使用一個版本的putIfAbsent(...),你可以提供某種工廠方法,以便在它尚未存在的情況下實例化一個Object。 這將簡化許多代碼。

這是我修改過的界面:

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你想要什么?

如果指定的鍵尚未與值關聯(或映射為null),則嘗試使用給定的映射函數計算其值,並將其輸入此映射,除非為null。

實現類似於:

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

所以它並不完全是您發布的Supplier<V>簽名,但接近於此。 在映射函數中使用key作為參數絕對有意義。

computeIfAbsent不是1:1替代的putIfAbsent,因為返回的值約束不匹配。 雖然putIfAbsent在創建新條目時返回null ,但computeIfAbsent始終返回指定的值。

上面建議的默認實現,調用get然后put工作,但它需要在map中進行兩次查找,這會破壞高性能原位替換的想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM