English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
If the key already exists in the hash key, the Java HashMap computeIfPresent() method will calculate a new value and associate it with the specified key.
The syntax of computeIfPresent() method is: }}
hashmap.computeIfPresent(K key, BiFunction remappingFunction)
computeIfPresent() method has two parameters:
key - key associated with the calculated value
remappingFunction - For the specifiedKeyFunction to calculate the new value
Note:The remappingFunction can accept two parameters.
Return the new value associated with the specified key
If there is no value associated with the key, then return null
Note:If the remappingFunction result is null, the specifiedKeymapping.
import java.util.HashMap; class Main { public static void main(String[] args) { // Creating HashMap HashMap<String, Integer> prices = new HashMap<>(); // Inserting entries into the HashMap prices.put("Shoes", 200); prices.put("Bag", 300); prices.put("Pant", 150); System.out.println("HashMap: ") + prices); //Using10Recompute the value of shoes with the VAT rate int shoesPrice = prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100); System.out.println("Price of shoes after adding VAT: ") + shoesPrice); // Print the updated HashMap System.out.println("Updated HashMap: ") + prices); } }
Output result
HashMap: {Pant=150, Bag=300, Shoes=200} Price of shoes after adding VAT: 220 Updated HashMap: {Pant=150, Bag=300, Shoes=220}}
In the above example, we created a hash map named prices. Note the expression
prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100)
Here,
(key, value) -> value + value*10/100 - It is a lambda expression. It calculates the new value of Shoes and returns. For more information about lambda expressions, please visitJava Lambda Expressions.
prices.computeIfPresent() - Associates the new value returned by the lambda expression with the Shoes mapping. This is the only possible because Shoes is already mapped to the value in the hash map.
The computeIfPresent() method cannot be used if the key does not exist in the hash table.
Recommended Reading
HashMap compute() - Computes the value of the specified key
HashMap computeIfAbsent() - Computes the value if the specified key is not mapped to any value
Java HashMap merge() - Performs the same task as compute()