Java HashMap computeIfPresent() Method

Java HashMap Java HashMap

The computeIfPresent() method recomputes the value of the specified key in the hashMap, provided that the key exists in the hashMap.

The syntax of 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 recompute the value

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 computeIfPresent() method:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<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 value of the 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);

        // Output 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 above example, we created a HashMap named prices.

Notice the expression:

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

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

To learn more about lambda expressions, please visitJava Lambda Expressions。

Java HashMap Java HashMap

Other Extensions