Java HashMap compute()

The syntax of the compute() method is:

hashmap.compute(K key, BiFunction remappingFunction)

Here, hashmap is an object of the HashMap class.


compute() Parameters

The compute() method takes 2 parameters:

  • key - key with which the computed value is to be associated
  • remappingFunction - function that computes the new value for the specified key

Note: The remappingFunction can take two arguments. Hence, considered as BiFunction.


compute() Return Value

  • returns the new value associated with the key
  • returns null if no value associated with key

Note: If remappingFunction results null, then the mapping for the specified key is removed.


Example: HashMap compute() to Insert New Value

import java.util.HashMap;

class Main {
  public static void main(String[] args) {
    // create an HashMap
    HashMap<String, Integer> prices = new HashMap<>();

    // insert entries to the HashMap
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("HashMap: " + prices);

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

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

Output

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 have created a hashmap named prices. Notice the expression,

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

Here,

  • (key, value) -> value - value * 10/100 - It is a lambda expression. It reduces the old value of Shoes by 10% and returns it. To learn more about the lambda expression, visit Java Lambda Expressions.
  • prices.compute() - Associates the new value returned by lambda expression to the mapping for Shoes.

We have used lambda expression as remapping function that rakes two parameters.

Note: According to the official documentation of Java, the HashMap merge() method is simpler than the compute() method.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges