Java HashMap的computeIfAbsent()方法計(jì)算一個(gè)新值,如果該鍵沒(méi)有與哈希映射中的任何值相關(guān)聯(lián),則將其與指定的鍵相關(guān)聯(lián)。
computeIfAbsent()方法的語(yǔ)法為:
hashmap.computeIfAbsent(K key, Function remappingFunction)
computeIfAbsent()方法有兩個(gè)參數(shù):
key - 與計(jì)算值關(guān)聯(lián)的鍵
remappingFunction - 為指定鍵計(jì)算新值的函數(shù)
注意:remapping function不能接受兩個(gè)參數(shù)。
返回與指定鍵關(guān)聯(lián)的新值或舊值
為指定鍵計(jì)算新值的函數(shù)
注意:如果remappingFunction結(jié)果為null,則將刪除指定鍵的映射。
import java.util.HashMap; class Main { public static void main(String[] args) { // 創(chuàng)建 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); // 計(jì)算襯衫的價(jià)值 int shirtPrice = prices.computeIfAbsent("Shirt", key -> 280); System.out.println("襯衫的價(jià)格: " + shirtPrice); // 打印更新HashMap System.out.println("更新后的 HashMap: " + prices); } }
輸出結(jié)果
HashMap: {Pant=150, Bag=300, Shoes=200} 襯衫的價(jià)格: 280 更新后的 HashMap: {Pant=150, Shirt=280, Bag=300, Shoes=200}
在上面的示例中,我們創(chuàng)建了一個(gè)名為prices的哈希映射。注意表達(dá)式
prices.computeIfAbsent("Shirt", key -> 280)
這里,
key -> 280 - 是lambda表達(dá)式。它返回值280。要了解有關(guān)lambda表達(dá)式的更多信息,請(qǐng)?jiān)L問(wèn)Java Lambda 表達(dá)式。
prices.computeIfAbsent() - 將lambda表達(dá)式返回的新值與Shirt的映射相關(guān)聯(lián)。這是可能的,因?yàn)镾hirt還沒(méi)有映射到hashmap中的任何值。
import java.util.HashMap; class Main { public static void main(String[] args) { // 創(chuàng)建 HashMap HashMap<String, Integer> prices = new HashMap<>(); // 向HashMap插入條目 prices.put("Shoes", 180); prices.put("Bag", 300); prices.put("Pant", 150); System.out.println("HashMap: " + prices); //Shoes 的映射已經(jīng)存在 //不計(jì)算Shoes的新值 int shoePrice = prices.computeIfAbsent("Shoes", (key) -> 280); System.out.println("鞋子價(jià)格: " + shoePrice); //打印更新的HashMap System.out.println("更新后的 HashMap: " + prices); } }
輸出結(jié)果
HashMap: {Pant=150, Bag=300, Shoes=180} 鞋子價(jià)格: 180 更新后的 HashMap: {Pant=150, Bag=300, Shoes=180}
在以上示例中,Shoes的映射已經(jīng)存在于哈希映射中。 因此,computeIfAbsent()方法不會(huì)計(jì)算Shoes的新值。
推薦閱讀
HashMap compute() - 計(jì)算指定鍵的值
HashMap computeIfPresent() - 如果指定的鍵已經(jīng)映射到一個(gè)值,則計(jì)算該值
Java HashMap merge() - 與compute()執(zhí)行相同的任務(wù)