The syntax of the putIfAbsent() method is:
hashmap.putIfAbsent(K key, V value)
Here, hashmap is an object of the HashMap class.
putIfAbsent() Parameters
The putIfAbsent() method takes two parameters.
- key - the specified value is associated with this key
- value - the specified key is mapped with this value
putAbsent() Return Value
- returns the value associated with the key, if the specified key is already present in the hashmap
- returns null, if the specified key is already not present in the hashmap
Note: If the specified key is previously associated with a null value, then also the method returns null.
Example 1: Java HashMap putIfAbsent()
Output
Languages: {1=Python, 2=C, 3=Java}
Updated Languages: {1=Python, 2=C, 3=Java, 4=JavaScript}
In the above example, we have created a hashmap named languages. Notice the line,
languages.putIfAbsent(4, "JavaScript");
Here, the key 4 is not already associated with any value. Hence, the putifAbsent() method adds the mapping {4 = JavaScript} to the hashmap.
Notice the line,
languages.putIfAbsent(2, "Swift");
Here, the key 2 is already associated with value Java. Hence, the putIfAbsent() method does not add the mapping {2 = Swift} to the hashmap.
Note: We have used the put() method to add a single mapping to the hashmap. To learn more, visit Java HashMap put().