Java HashMap computeIfAbsent() Method
The computeIfAbsent() method recalculates the value for the specified key in the hashMap; if the key does not exist, it is added to the hashMap.
The syntax of computeIfAbsent() is:
hashmap.computeIfAbsent(K key, Function remappingFunction)
Note:hashmap is an object of the HashMap class.
Parameter Details:
- key - the key
- remappingFunction - the remapping function, used to recalculate the value
Return Value
If the value corresponding to the key does not exist, the value recalculated by remappingFunction is obtained and stored as the value for that key; otherwise, the value is returned.
Example
The following example demonstrates the use of the computeIfAbsent() method:
Example
class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<String, Integer> prices = new HashMap<>();
// Add mapping entries to the HashMap
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: " + prices);
// Compute the value for Shirt
int shirtPrice = prices.computeIfAbsent("Shirt", key -> 280);
System.out.println("Price of Shirt: " + shirtPrice);
// Output the updated HashMap
System.out.println("Updated HashMap: " + prices);
}
}
The output of the above program is:
HashMap: {Pant=150, Bag=300, Shoes=200}
Price of Shirt: 280
Updated HashMap: {Pant=150, Shirt=280, Bag=300, Shoes=200}
In the above example, we created a HashMap named prices.
Note the expression:
prices.computeIfAbsent("Shirt", key -> 280)
In the code, we used an anonymous function, a lambda expression.key-> 280As the remapping function, prices.computeIfAbsent() associates the new value returned by the lambda expression with Shirt.
Because Shirt does not exist in the HashMap, a new key/value pair is added.
To learn more about lambda expressions, visitJava Lambda Expressions。
Case when the key already exists:
Example
class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<String, Integer> prices = new HashMap<>();
// Add mapping relationships to the HashMap
prices.put("Shoes", 180);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: " + prices);
// The mapping for Shoes already exists
// No new value is computed for Shoes
int shoePrice = prices.computeIfAbsent("Shoes", (key) -> 280);
System.out.println("Price of Shoes: " + shoePrice);
// Output the updated HashMap
System.out.println("Updated HashMap: " + prices);
}
}
The output of the above program is:
HashMap: {Pant=150, Bag=300, Shoes=180}
Price of Shoes: 180
Updated HashMap: {Pant=150, Bag=300, Shoes=180}In the above example, the mapping for Shoes already exists in the HashMap, so no new value is computed for Shoes.
Other Extensions
Java HashMap