The
java.util.concurrent.ConcurrentHashMap.putIfAbsent() is an in-built function in Java which accepts a key and a value as parameters and maps them if the specified key is not mapped to any value.
Syntax:
chm.putIfAbsent(key_elem, val_elem)
Parameters: The function accepts two parameters which are described below:
- key_elem: This parameter specifies the key to which the specified val_elem is to be mapped if key_elem is not associated with any value.
- val_elem: This parameter specifies the value to be mapped to the specified key_elem.
Return Value: The function returns the existing value mapped to the key and returns null if no value is previously mapped to the key.
Exception: The function throws
NullPointerException when the specified parameters are null.
Below programs illustrate the ConcurrentHashMap.putIfAbsent() method :
Program 1: An existing key is passed as parameter to the function.
Output:
Initial Mappings are: {100=Geeks, 101=for, 102=Geeks, 103=Gfg, 104=GFG}
Returned value is: null
New mappings are: {100=Geeks, 101=for, 102=Geeks, 103=Gfg, 104=GFG, 108=All}
Program 2: A non-existing key is passed as parameter to the function.