In Java, the computeIfAbsent() method of the HashMap class is used to compute and insert a value for a specific key to a HashMap only if the key does not already have a value.
Example 1: Here, the computeIfAbsent() adds a value for a key if it is not present in the map and does nothing if the key is present in the map.
// Java program to demonstrate the
// working of computeIfAbsent()
import java.util.HashMap;
public class Geeks {
public static void main(String[] args) {
HashMap<String, Integer> hm = new HashMap<>();
// Adding initial values to the map
hm.put("A", 1);
hm.put("B", 2);
System.out.println("Initial Map: " + hm);
// Using computeIfAbsent()
Integer i
= hm.computeIfAbsent("C", key -> key.length());
Integer j
= hm.computeIfAbsent("A", key -> key.length());
// the key "C" is not present in the
// map the value is computed
System.out.println("Value for C: " + i);
// the key "A" is present in the
// map the value is not recomputed
System.out.println("Value for A: " + j);
System.out.println("Updated Map: " + hm);
}
}
Output
Initial Map: {A=1, B=2}
Value for C: 1
Value for A: 1
Updated Map: {A=1, B=2, C=1}
Syntax of computeIfAbsent() Method
public V computeIfAbsent(K key, Function mappingFunction)
Parameters:
- Key: The key whose associated value is to be calculated.
- mappingFunction: It is a function that computes the value if the key is not present.
Return Type:
- If the key is present, then it returns the existing value.
- If the key is not present, it calculates the value using mappingFunction and then returns the calculated value.
Key Points:
- If remapping function returns null for a key, then no mapping is recorded for that key.
- At time of computation if remapping function throws an exception, the exception is rethrown, and the no mapping is recorded.
- This method will throw a ConcurrentModificationException if the remapping function modified this map during computation.
Example 2: Here, the computeIfAbsent() return the existing value for a key if it is already present in the map.
// Handling Existing Keys
import java.util.HashMap;
public class Geeks {
public static void main(String[] args)
{
HashMap<String, String> hm = new HashMap<>();
// Adding initial values to the map
hm.put("A", "1");
hm.put("B", "2");
System.out.println("Initial Map: " + hm);
// Use computeIfAbsent for an existing key
String e
= hm.computeIfAbsent("A", key -> "New Value");
// Use computeIfAbsent for a new key
String n = hm.computeIfAbsent("C", key -> "3");
System.out.println("Value for existing key 'A': "
+ e);
System.out.println("Value for new key 'C': " + n);
System.out.println("Updated Map: " + hm);
}
}
Output
Initial Map: {A=1, B=2}
Value for existing key 'A': 1
Value for new key 'C': 3
Updated Map: {A=1, B=2, C=3}