Java HashMap
computeIfAbsent() 方法對 hashMap 中指定 key 的值進行重新計算,如果不存在這個 key,則添加到 hashMap 中。
computeIfAbsent() 方法的文法為:
hashmap.computeIfAbsent(K key, Function remappingFunction)
注:hashmap 是 HashMap 類的一個對象。
參數說明:
- key - 鍵
- remappingFunction - 重新映射函數,用于重新計算值
傳回值
如果 key 對應的 value 不存在,則使用擷取 remappingFunction 重新計算後的值,并儲存為該 key 的 value,否則傳回 value。
執行個體
以下執行個體示範了 computeIfAbsent() 方法的使用:
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// 建立一個 HashMap
HashMap<String, Integer> prices = new HashMap<>();
// 往HashMap中添加映射項
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: " + prices);
// 計算 Shirt 的值
int shirtPrice = prices.computeIfAbsent("Shirt", key -> 280);
System.out.println("Price of Shirt: " + shirtPrice);
// 輸出更新後的HashMap
System.out.println("Updated HashMap: " + prices);
}
}
執行以上程式輸出結果為:
HashMap: {Pant=150, Bag=300, Shoes=200}
Price of Shirt: 280
Updated HashMap: {Pant=150, Shirt=280, Bag=300, Shoes=200}
在以上執行個體中,我們建立了一個名為 prices 的 HashMap。
注意表達式:
prices.computeIfAbsent("Shirt", key -> 280)
代碼中,我們使用了匿名函數 lambda 表達式 key-> 280 作為重新映射函數,prices.computeIfAbsent() 将 lambda 表達式傳回的新值關聯到 Shirt。
因為 Shirt 在 HashMap 中不存在,是以是新增了 key/value 對。
要了解有關 lambda 表達式的更多資訊,請通路 Java Lambda 表達式。
當 key 已經存在的情況:
// 往HashMap中添加映射關系
prices.put("Shoes", 180);
// Shoes中的映射關系已經存在
// Shoes并沒有計算新值
int shoePrice = prices.computeIfAbsent("Shoes", (key) -> 280);
System.out.println("Price of Shoes: " + shoePrice);
// 輸出更新後的 HashMap
HashMap: {Pant=150, Bag=300, Shoes=180}
Price of Shoes: 180
Updated HashMap: {Pant=150, Bag=300, Shoes=180}
在以上執行個體中, Shoes 的映射關系在 HashMap 中已經存在,是以不會為 Shoes 計算新值。
Java HashMap