What is the HashMap computeIfAbsent() method in Java?

The computeIfAbsent() method of the HashMap class in Java maps a new value to a provided key, given that the key does not already have an associated value.

The process is illustrated below:

To use the computeIfAbsent() method, you will need to import the HashMap class into the program, as shown below:

import java.util.HashMap;

The prototype of the computeIfAbsent() method is shown below:

public computeIfAbsent(K key, Function mappingFunction)

Parameters

The computeIfAbsent() method takes the following parameters:

  • key: The key for which the value must be computed.
  • mappingFunction: The function that computes the new value.

Return value

The computeIfAbsent() method checks the value associated with the provided key parameter and returns one of the following:

  • If key has an associated value, the value is returned and no new value is computed.

  • If key does not have an associated value, a new value is computed and returned.

  • If mappingFunction returns null, then computeIfAbsent() also returns null.

Example

The code below shows how the computeIfAbsent() method works in Java:

import java.util.HashMap;
class Main {
public static void main(String[] args)
{
// initializing HashMap
HashMap<String, Integer> quantities = new HashMap<>();
// populating HashMap
quantities.put("Apples", 10);
quantities.put("Bananas", 2);
quantities.put("Oranges", 5);
// original quantities
System.out.println("The original quantities are: " + quantities);
// key not present
int peach_quantity = quantities.computeIfAbsent("Peach", key -> 15);
// key already present
int banana_quantity = quantities.computeIfAbsent("Bananas", key -> 30);
// new quantities
System.out.println("The new quantities are: " + quantities);
System.out.println("Peach quantity: " + peach_quantity);
System.out.println("Banana quantity: " + banana_quantity);
}
}

Explanation

First, a HashMap object quantities is initialized.

Next, key-value pairs are inserted into the HashMap. All entries have unique values.

The computeIfAbsent() method in line 1818 proceeds to iterate over each mapping in the HashMap to find the value associated with the key “Peach”. Since “Peach” does not exist in the HashMap, the computeIfAbsent() method creates a mapping for the new key with the specified value 1515, and returns the new value.

Similarly, the computeIfAbsent() method in line 2121 proceeds to iterate over each mapping in the HashMap to find the value associated with the key “Bananas”. Since “Bananas” already has an associated value, the computeIfAbsent() method does not compute a new value and returns the old value, i.e., 22.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved