Last Updated : 11 Jul, 2025
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
// 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);
}
}
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:
Return Type:
Key Points:
Example 2: Here, the computeIfAbsent() return the existing value for a key if it is already present in the map.
Java
// 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);
}
}
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}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4