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()
import java.util.HashMap;
class Main {
public static void main(String[] args){
// create a HashMap
HashMap<Integer, String> languages = new HashMap<>();
// add mappings to HashMap
languages.put(1, "Python");
languages.put(2, "C");
languages.put(3, "Java");
System.out.println("Languages: " + languages);
// key already not present in HashMap
languages.putIfAbsent(4, "JavaScript");
// key already present in HashMap
languages.putIfAbsent(2, "Swift");
System.out.println("Updated Languages: " + languages);
}
}
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().