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)
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.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
.
The code below shows how the computeIfAbsent()
method works in Java:
import java.util.HashMap;class Main {public static void main(String[] args){// initializing HashMapHashMap<String, Integer> quantities = new HashMap<>();// populating HashMapquantities.put("Apples", 10);quantities.put("Bananas", 2);quantities.put("Oranges", 5);// original quantitiesSystem.out.println("The original quantities are: " + quantities);// key not presentint peach_quantity = quantities.computeIfAbsent("Peach", key -> 15);// key already presentint banana_quantity = quantities.computeIfAbsent("Bananas", key -> 30);// new quantitiesSystem.out.println("The new quantities are: " + quantities);System.out.println("Peach quantity: " + peach_quantity);System.out.println("Banana quantity: " + banana_quantity);}}
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 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 , and returns the new value.
Similarly, the computeIfAbsent()
method in line 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., .
Free Resources