Let's suppose that we have the following Map:
Map<Integer, String> map = new HashMap<>();
map.put(1, "postgresql");
map.put(2, "mysql");
map.put(3, null);
We use this map to store the names of some database types.
Now, let's suppose that we want to include more database types in this map based on the following constraints:
- If the given key is present in the map, then simply return the corresponding value and leave the map untouched.
- If the given key is not present in the map (or is associated with a null value), then put the given value in the map and return null.
Well, this is a job for putIfAbsent​(K key, V value).
The following three attempts speak for themselves:
String v1 = map.putIfAbsent(1, "derby"); // postgresql
String v2 = map.putIfAbsent(3, "derby"); // null
String v3 = map.putIfAbsent(4, "cassandra"); // null
And the map content is as follows:
1=postgresql, 2=mysql, 3=derby, 4=cassandra