The putIfAbsent() method of the HashMap class in Java is used to insert a key-value pair into the map only if the key is not present in the map or is mapped to null. The existing value remains unchanged if the key is already associated with a value.
Example 1: In this example, we will demonstrate the basic usage of the putIfAbsent() method.
import java.util.HashMap;
public class Geeks {
public static void main(String[] args)
{
// Create a HashMap
HashMap<Integer, String> hm = new HashMap<>();
// Insert some values
hm.put(1, "Geek1");
hm.put(2, "Geek2");
// Use putIfAbsent
System.out.println("Before putIfAbsent(): " + hm);
// Key does not exist, so the value is inserted
hm.putIfAbsent(3, "Geek3");
// Key exists, so the value is not inserted
hm.putIfAbsent(1, "Geek4");
System.out.println("After putIfAbsent(): " + hm);
}
}
Output
Before putIfAbsent(): {1=Geek1, 2=Geek2}
After putIfAbsent(): {1=Geek1, 2=Geek2, 3=Geek3}
Explanation: In the above example, the Key 3 is not present, so it gets added with the value "Geek3". The Key 1 already exists, so the value "Geek1" remains unchanged.
Syntax of putIfAbsent() Method
default V putIfAbsent(K key, V value)
V: The return type of the method. It represents the type of the value associated with the key in the HashMap.
Parameters:
- key: The key with which the specified value is to be associated.
- value: The value to be associated with the specified key.
Return Type: This method return previous value associated with the specified key or return null if there was no mapping for the key.
Key Points: