Easy Tutorial
❮ Dir Root Dir Size ❯

Java HashMap compute() Method

The compute() method recomputes the value for the specified key in a hashMap.

The syntax for the compute() method is:

hashmap.compute(K key, BiFunction remappingFunction)

Note: hashmap is an object of the HashMap class.

Parameter Description:

Return Value

If the value corresponding to the key does not exist, it returns null; if it exists, it returns the value recomputed by the remappingFunction.

Example

The following example demonstrates the use of the compute() 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);

        // Recompute the price of shoes after a 10% discount
        int newPrice = prices.compute("Shoes", (key, value) -> value - value * 10/100);
        System.out.println("Discounted Price of Shoes: " + newPrice);

        // Print the updated HashMap
        System.out.println("Updated HashMap: " + prices);
    }
}

Executing the above program outputs:

HashMap: {Pant=150, Bag=300, Shoes=200}
Discounted Price of Shoes: 180
Updated HashMap: {Pant=150, Bag=300, Shoes=180}

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

Note the expression:

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

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

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

❮ Dir Root Dir Size ❯