In Java, the HashMap
class provides a convenient method called computeIfAbsent()
that allows you to retrieve a value from the map based on a key, and if the key is not present in the map, it computes a new value using a specified function and adds it to the map.
Here’s an example of using the computeIfAbsent()
method to add a new key-value mapping to a HashMap
:
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
// Create a new HashMap
Map<String, Integer> map = new HashMap<>();
// Add some key-value mappings to the map
map.put("John", 28);
map.put("Alice", 35);
// Compute a new value for a key that is not present in the map
Integer bobAge = map.computeIfAbsent("Bob", key -> {
// This lambda function will be called to compute a new value
// for the "Bob" key because it is not present in the map
System.out.println("Computing new age for Bob...");
return 42;
});
System.out.println("Bob's age is " + bobAge);
System.out.println(map);
}
}
In this example, we create a new HashMap
called map
and add two key-value mappings to it. We then use the computeIfAbsent()
method to retrieve the age of a person named “Bob” from the map. Since “Bob” is not present in the map, the lambda function passed as the second argument to computeIfAbsent()
will be called to compute a new age for Bob.
Inside the lambda function, we print a message to the console and return the value 42
, which will be added to the map as the age of “Bob”. The computeIfAbsent()
method returns the value 42
, which we store in the bobAge
variable.
Finally, we print out the age of “Bob” using System.out.println()
and also print the contents of the map using System.out.println(map)
to verify that the new key-value mapping for “Bob” has been added to the map. The output of this program would be:
Computing new age for Bob...
Bob's age is 42
{John=28, Alice=35, Bob=42}
This demonstrates how to use the computeIfAbsent()
method to add a new key-value mapping to a HashMap
if the key is not present in the map.