In Java, putIfAbsent(key, value) stores value only when key is not in the TreeMap yet, or is mapped to null. If the key already has a non-null value, the map is left alone and that value is returned.
It replaces the common two-step pattern "if (!map.containsKey(k)) map.put(k, v);" with one call and one O(log n) search. Typical uses are "first one wins" records and filling in default settings without overwriting the user's choices.
An instance method of java.util.TreeMap, added in Java 8 as part of the Map interface. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe. TreeMap has its own implementation since Java 15 (earlier versions use the Map default); the behaviour is the same.
Syntax
Pass the key and the value to use if the key is free.
Example 1 — Record the Day Each User First Visited
A visit log repeats names; keep only the first day for each user.
Java
import java.util.TreeMap;
public class TreeMapPutIfAbsentFirstVisit {
public static void main(String[] args) {
TreeMap<String, Integer> firstVisit = new TreeMap<>();
String[] log = {"kai", "ana", "kai", "zoe", "ana"};
for (int day = 0; day < log.length; day++) {
Integer before = firstVisit.putIfAbsent(log[day], day + 1);
if (before != null) {
System.out.println(log[day] + " already seen on day " + before);
}
}
System.out.println(firstVisit);
}
}
Output
kai already seen on day 1
ana already seen on day 2
{ana=2, kai=1, zoe=4}
How It Works
New names are stored. On days 1, 2, and 4 the names kai, ana, and zoe are new, so putIfAbsent stores the day and returns null.
Repeat visits report the first day. On days 3 and 5 the name exists; the call returns the stored day (1 for kai, 2 for ana) and leaves it unchanged.
Sorted record. The final map lists ana, kai, zoe alphabetically, each with the earliest day seen.
Example 2 — A Key Mapped to null Gets Filled In
Lena has a mentor slot with a null value. See which calls change the map.
Java
import java.util.TreeMap;
public class TreeMapPutIfAbsentNullValue {
public static void main(String[] args) {
TreeMap<String, String> mentors = new TreeMap<>();
mentors.put("Ravi", "Dana");
mentors.put("Lena", null);
String r1 = mentors.putIfAbsent("Ravi", "Omar");
String r2 = mentors.putIfAbsent("Lena", "Omar");
String r3 = mentors.putIfAbsent("Theo", "Kim");
System.out.println("Ravi: returned " + r1);
System.out.println("Lena: returned " + r2);
System.out.println("Theo: returned " + r3);
System.out.println(mentors);
}
}
Output
Ravi: returned Dana
Lena: returned null
Theo: returned null
{Lena=Omar, Ravi=Dana, Theo=Kim}
How It Works
Ravi keeps Dana. His value is non-null, so Omar is ignored and Dana is returned.
Lena's null is replaced. A null value counts as "absent", so Omar is stored and the call returns null, exactly as for the brand-new key Theo.
Read null with care. A null result means "stored now" for both Lena and Theo; it does not tell you whether the key existed before.
Example 3 — Fill Missing Settings From Defaults
The user chose a theme and font size. Copy only the defaults that are still missing.
Java
import java.util.Map;
import java.util.TreeMap;
public class TreeMapPutIfAbsentDefaults {
public static void main(String[] args) {
TreeMap<String, String> settings = new TreeMap<>();
settings.put("theme", "dark");
settings.put("fontSize", "18");
TreeMap<String, String> defaults = new TreeMap<>();
defaults.put("fontSize", "14");
defaults.put("language", "en");
defaults.put("theme", "light");
int added = 0;
for (Map.Entry<String, String> d : defaults.entrySet()) {
if (settings.putIfAbsent(d.getKey(), d.getValue()) == null) {
added++;
}
}
System.out.println(settings);
System.out.println("defaults added: " + added);
}
}