![]() |
VOOZH | about |
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.
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.
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:
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:
Example 2: In this example, we will see how putIfAbsent() method handles null values and return values.
Original HashMap: {A=100, B=200, C=null}
Result for Key D (absent): null
Result for Key C (null): null
Result for Key A (existing): 100
Updated HashMap: {A=100, B=200, C=300, D=400}
Explanation: In the above example, the Key D is added because it is not present in the map. The Key C is mapped to null, so it is updated with the value 300. The Key A exists with a value of 100, so no change occurs.