The syntax of the computeIfPresent()
method is:
hashmap.computeIfPresent(K key, BiFunction remappingFunction)
Here, hashmap is an object of the HashMap class.
computeIfPresent() Parameters
The computeIfPresent()
method takes 2 parameters:
- key - key with which the computed value is to be associated
- remappingFunction - function that computes the new value for the specified key
Note: The remappingFunction can take two arguments. Hence, considered as BiFunction.
computeIfPresent() Return Value
- returns the new value associated with the specified key
- returns
null
if no value associated with key
Note: If remappingFunction results null
, then the mapping for the specified key is removed.
Example 1: Java HashMap computeIfPresent()
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// create an HashMap
HashMap<String, Integer> prices = new HashMap<>();
// insert entries to the HashMap
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: " + prices);
// recompute the value of Shoes with 10% VAT
int shoesPrice = prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100);
System.out.println("Price of Shoes after VAT: " + shoesPrice);
// print updated HashMap
System.out.println("Updated HashMap: " + prices);
}
}
Output
HashMap: {Pant=150, Bag=300, Shoes=200} Price of Shoes after VAT: 220 Updated HashMap: {Pant=150, Bag=300, Shoes=220}}
In the above example, we have created a hashmap named prices. Notice the expression,
prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100)
Here,
- (key, value) -> value + value*10/100 is a lambda expression. It computes the new value of Shoes and returns it. To learn more about the lambda expression, visit Java Lambda Expressions.
- prices.computeIfPresent() associates the new value returned by lambda expression to the mapping for Shoes. It is only possible because Shoes is already mapped to a value in the hashmap.
Here, the lambda expression acts as remapping function. And, it takes two parameters.
Note: We cannot use the computeIfPresent()
method if the key is not present in the hashmap.
Also Read: