Introduced in Java 8, the putIfAbsent() method is part of the java.util.Map interface and is widely
used to simplify conditional insertions. It allows you to insert a new value for a given key only if that key is not already
associated with a value or is currently mapped to null. This makes it a cleaner alternative to manually checking for key
existence before updating a map.
The default implementation for putIfAbsent() is as given below. As you can see just by using single method putIfAbsent()
you get the logic of checking whether the key is already present or not in the map and putting the value in case key is
not there (or associated value is null).
V v = map.get(key);
if (v == null)
v = map.put(key, value);
return v;
Alongside putIfAbsent(), there is also a
computeIfAbsent() method in Java, which also puts a value if specified key is not already associated with a value
but with one key difference, instead of directly inserting a value, it computes the value using a provided mapping function
if the key is not already present.
Syntax of the putIfAbsent () method is as given below.
V putIfAbsent(K key, V value)
Parameters are as-
- key- key with which the specified value is to be associated
- value- value to be associated with the specified key
Method returns the previous value if the specified key is already associated with the value.
Returns null if specified key is not already present in the Map, which actually means key is absent and the method is
inserting the given key, value pair in the Map. It may also mean that the key is present but associated with null value.
putIfAbsent() Java examples
1. In the first example we'll have a map of cities and we'll try to insert a new city with a key which already
exists in the HashMap.
import java.util.HashMap;
import java.util.Map;
public class PutIfAbsentDemo {
public static void main(String[] args) {
// Setting up a HashMap
Map<String, String> cityMap = new HashMap<String, String>();
cityMap.put("1","New York City" );
cityMap.put("2", "New Delhi");
cityMap.put("3", "Mumbai");
cityMap.put("4", "Berlin");
String val = cityMap.putIfAbsent("4", "London");
System.out.println("Value is- " + val);
System.out.println(cityMap);
}
}
Output
Value is- Berlin
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
Since key already exists and mapped with a value in the HashMap so putIfAbsent() method won't replace the previous value
with new value for the same key. Also notice the return value of the method which is the value associated with the
specified key.
2. In this example we'll try to insert a new city with a key which is not already there in the Map.
public class PutIfAbsentDemo {
public static void main(String[] args) {
// Setting up a HashMap
Map<String, String> cityMap = new HashMap<String, String>();
cityMap.put("1","New York City" );
cityMap.put("2", "New Delhi");
cityMap.put("3", "Mumbai");
cityMap.put("4", "Berlin");
String val = cityMap.putIfAbsent("5", "London");
System.out.println("Value is- " + val);
System.out.println(cityMap);
}
}
Output
Value is- null
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin, 5=London}
Since key is not there in the Map so a new entry is added to the HashMap. Also notice the return value of the putifAbsent()
method which is null this time because there was no mapping for the key.
3. In this example we'll take the scenario when the key exists in the HashMap but mapped with null.
public class PutIfAbsentDemo {
public static void main(String[] args) {
// Setting up a HashMap
Map<String, String> cityMap = new HashMap<String, String>();
cityMap.put("1","New York City" );
cityMap.put("2", "New Delhi");
cityMap.put("3", "Mumbai");
cityMap.put("4", null);
String val = cityMap.putIfAbsent("4", "London");
System.out.println("Value is- " + val);
System.out.println(cityMap);
}
}
Output
Value is- null
{1=New York City, 2=New Delhi, 3=Mumbai, 4=London}
Since the key is mapped to null so putIfAbsent() method associates the key with a new value.
That's all for this topic Java Map putIfAbsent() With Examples. If you have any doubt or any suggestions to
make please drop a comment. Thanks!
Related Topics
-
Java Map merge() With Examples
-
Java Map getOrDefault() Method With Examples
-
Map.Entry Interface in Java
-
EnumSet in Java With Examples
-
Java Collections Interview Questions And Answers
You may also like-
-
Java StampedLock With Examples
-
CopyOnWriteArraySet in Java With Examples
-
Garbage Collection in Java
-
Difference Between Checked And Unchecked Exceptions in Java
-
How to Read Excel File in Java Using Apache POI
-
Spring Boot StandAlone (Console Based) Application Example
-
Spring MVC Exception Handling - @ExceptionHandler And @ControllerAdvice Example
-
Angular @HostBinding Decorator With Examples