Java Hashmap Computeifpresent
# Java HashMap computeIfPresent() Method
[ Java HashMap](#)
The computeIfPresent() method recalculates the value for a specified key in a HashMap, provided that the key exists in the HashMap.
The syntax for the computeIfPresent() method is:
hashmap.computeIfPresent(K key, BiFunction remappingFunction)
**Note:** hashmap is an object of the HashMap class.
**Parameter Description:**
* key - The key
* remappingFunction - The remapping function used to recalculate the value
### Return Value
If the value corresponding to the key does not exist, it returns null. If it exists, it returns the value recalculated by the remappingFunction.
### Example
The following example demonstrates the use of the computeIfPresent() method:
## Example
import java.util.HashMap;
class Main {
public static void main(String[] args){
// Create a HashMap
HashMap prices =new HashMap();
// Add mappings to the HashMap
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: "+ prices);
// Recalculate the value of shoes after adding 10% VAT
int shoesPrice = prices.computeIfPresent("Shoes", (key, value)-> value + value *10/100);
System.out.println("Price of Shoes after VAT: "+ shoesPrice);
// Print the updated HashMap
System.out.println("Updated HashMap: "+ prices);
}
}
Executing the above program outputs:
HashMap: {Pant=150, Bag=300, Shoes=200}Price of Shoes after VAT: 220Updated HashMap: {Pant=150, Bag=300, Shoes=220}}
In the above example, we created a HashMap named prices.
Note the expression:
prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100)
In the code, we used the anonymous function lambda expression (key, value) -> value + value * 10/100 as the remapping function.
To learn more about lambda expressions, visit (#).
[ Java HashMap](#)
YouTip