computeIfAbsent() 方法對 hashMap 中指定 key 的值進行重新計算违柏,如果不存在這個 key跳仿,則添加到 hashMap 中。
computeIfAbsent() 方法的語法為:
hashmap.computeIfAbsent(K key, Function remappingFunction)
注:hashmap 是 HashMap 類的一個對象留瞳。
參數說明:
key - 鍵
remappingFunction - 重新映射函數摸柄,用于重新計算值
返回值
如果 key 對應的 value 不存在沥寥,則使用獲取 remappingFunction 重新計算后的值碍舍,并保存為該 key 的 value,否則返回 value邑雅。
實例
以下實例演示了 computeIfAbsent() 方法的使用:
實例
importjava.util.HashMap;
classMain{
publicstaticvoidmain(String[]args){
// 創(chuàng)建一個 HashMap
HashMap<String, Integer>prices=newHashMap<>();
// 往HashMap中添加映射項
prices.put("Shoes",200);
prices.put("Bag",300);
prices.put("Pant",150);
System.out.println("HashMap: "+prices);
// 計算 Shirt 的值
intshirtPrice=prices.computeIfAbsent("Shirt", key->280);
System.out.println("Price of Shirt: "+shirtPrice);
// 輸出更新后的HashMap
System.out.println("Updated HashMap: "+prices);
}
}
執(zhí)行以上程序輸出結果為:
HashMap: {Pant=150, Bag=300, Shoes=200}Price of Shirt: 280Updated HashMap: {Pant=150, Shirt=280, Bag=300, Shoes=200}
在以上實例中片橡,我們創(chuàng)建了一個名為 prices 的 HashMap。
注意表達式:
prices.computeIfAbsent("Shirt", key -> 280)
代碼中淮野,我們使用了匿名函數? lambda 表達式key-> 280作為重新映射函數捧书,prices.computeIfAbsent() 將 lambda 表達式返回的新值關聯到 Shirt。
因為 Shirt 在 HashMap 中不存在骤星,所以是新增了 key/value 對经瓷。
要了解有關 lambda 表達式的更多信息,請訪問Java Lambda 表達式妈踊。
當 key 已經存在的情況:
實例
importjava.util.HashMap;
classMain{
publicstaticvoidmain(String[]args){
// 創(chuàng)建一個 HashMap
HashMap<String, Integer>prices=newHashMap<>();
// 往HashMap中添加映射關系
prices.put("Shoes",180);
prices.put("Bag",300);
prices.put("Pant",150);
System.out.println("HashMap: "+prices);
// Shoes中的映射關系已經存在
// Shoes并沒有計算新值
intshoePrice=prices.computeIfAbsent("Shoes",(key)->280);
System.out.println("Price of Shoes: "+shoePrice);
// 輸出更新后的 HashMap
System.out.println("Updated HashMap: "+prices);
}
}
執(zhí)行以上程序輸出結果為:
HashMap: {Pant=150, Bag=300, Shoes=180}Price of Shoes: 180Updated HashMap: {Pant=150, Bag=300, Shoes=180}
在以上實例中了嚎, Shoes 的映射關系在 HashMap 中已經存在泪漂,所以不會為 Shoes 計算新值廊营。