The computeIfPresent()
method of the HashMap
class in Java maps a new value to a provided key, given that the key is present in the HashMap
.
The process is illustrated below:
To use the computeIfPresent()
method, you will need to import the HashMap
class into the program, as shown below:
import java.util.HashMap;
The prototype of the computeIfPresent()
method is shown below:
public computeIfPresent(K key, BiFunction remappingFunction)
The computeIfPresent()
method takes the following parameters:
key
: The key for which the value must be computed.remappingFunction
: The function that computes the new value.The computeIfPresent()
method checks the value associated with the provided key
parameter and returns one of the following:
If key
has an associated value, a new value is computed and returned.
If key
does not have an associated value, then computeIfPresent()
returns null
.
Note: If the
remappingFunction
returnsnull
, the key-value pair is removed from theHashMap
.
The code below shows how the computeIfPresent()
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 already presentint banana_quantity = quantities.computeIfPresent("Bananas", (key, value) -> 30);// key not presentif(quantities.computeIfPresent("Peach", (key, value) -> 15) == null){System.out.println("The function returned null.");}// new quantitiesSystem.out.println("The new quantities are: " + quantities);}}
First, a HashMap
object quantities
is initialized.
Next, key-value pairs are inserted into the HashMap
. All entries have unique values.
The computeIfPresent()
method in line proceeds to iterate over each mapping in the HashMap
to find the value associated with the key “Bananas”. Since “Bananas” exists in the HashMap
, the computeIfPresent()
method computes a new value for the specified key, i.e., . The computeIfPresent()
method also returns the newly computed value.
Similarly, the computeIfPresent()
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 computeIfPresent()
method returns null
. As a result, the if-condition
in line is satisfied, and an error message is output.
Free Resources