Java HashMap computeIfAbsent()

The syntax of the computeIfAbsent() method is:

hashmap.computeIfAbsent(K key, Function remappingFunction)

Here, hashmap is an object of the HashMap class.


computeIfAbsent() Parameters

The computeIfAbsent() 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 remapping function cannot take two arguments.


computeIfAbsent() Return Value

  • returns the new or old value associated with the specified key
  • returns null if no value associated with key

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


Example 1: Java HashMap computeIfAbsent()

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);

    // compute the value of Shirt
    int shirtPrice = prices.computeIfAbsent("Shirt", key -> 280);
    System.out.println("Price of Shirt: " + shirtPrice);

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

Output

HashMap: {Pant=150, Bag=300, Shoes=200}
Price of Shirt: 280
Updated HashMap: {Pant=150, Shirt=280, Bag=300, Shoes=200}

In the above example, we have created a hashmap named prices. Notice the expression,

prices.computeIfAbsent("Shirt", key -> 280)

Here,

  • key -> 280 is a lambda expression. It returns the value 280. To learn more about the lambda expression, visit Java Lambda Expressions.
  • prices.computeIfAbsent() associates the new value returned by lambda expression to the mapping for Shirt. It is only possible because Shirt is already not mapped to any value in the hashmap.

Example 2: computeIfAbsent() if the key is already present

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", 180);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("HashMap: " + prices);

    // mapping for Shoes is already present
    // new value for Shoes is not computed
    int shoePrice = prices.computeIfAbsent("Shoes", (key) -> 280);
    System.out.println("Price of Shoes: " + shoePrice);

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

Output

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

In the above example, the mapping for Shoes is already present in the hashmap. Hence, the computeIfAbsent() method does not compute the new value for Shoes.


Also Read:

Did you find this article helpful?