Easy Tutorial
❮ File Read Only Data Vecsort ❯

Java HashMap computeIfPresent() Method

The computeIfPresent() method recalculates the value of a specified key in a hashMap if 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:

Return Value

Returns null if the value for the key does not exist; otherwise, returns the value recalculated by the remappingFunction.

Example

The following example demonstrates the use of the computeIfPresent() method:

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap&lt;String, Integer> 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 price of shoes after adding a 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: 220
Updated HashMap: {Pant=150, Bag=300, Shoes=220}

In the example above, we created a HashMap named prices.

Note the expression:

prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100)

In the code, we used a lambda expression (key, value) -> value + value * 10/100 as the remapping function.

To learn more about lambda expressions, visit Java Lambda Expressions.

❮ File Read Only Data Vecsort ❯