Java TreeMap putIfAbsent() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

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.

Java
TreeMap<String, Integer> firstVisit = new TreeMap<>();
firstVisit.putIfAbsent("kai", 1);   // null: added
firstVisit.putIfAbsent("kai", 3);   // 1: kept, nothing changes
CallWhat it does
map.putIfAbsent(k, v)Adds v if k is missing or maps to null.
map.putIfAbsent(k, v) == nulltrue when the value was stored.
map.computeIfAbsent(k, f)Builds the value only when it is needed.

The value argument is evaluated even when it is not stored. If creating it is expensive, use computeIfAbsent() instead.

Library declarations
Java
// java.util.TreeMap<K, V>
public V putIfAbsent(K key, V value)

// Default method of Map<K, V> since Java 8; TreeMap overrides it since Java 15

Parameters

ParameterDescription
key (K)The key to check. Not null under natural ordering.
value (V)The value to store if the key is absent.

Return Value

Return ValueDescription
VThe existing non-null value; the map was not changed.
nullThe value was stored (the key was missing or mapped to null).

Compare with Similar Methods

Conditional inserts compared:

MethodHow it differs
put(k, v)Always stores, overwriting any old value.
computeIfAbsent(k, f)Same idea, but the value comes from a function called only if needed.
replace(k, v)The opposite: only changes keys that exist.
HashMap.putIfAbsentSame rules on an unordered map.

Java Examples

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);
    }
}

How It Works

  1. 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.
  2. 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.
  3. 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);
    }
}

How It Works

  1. Ravi keeps Dana. His value is non-null, so Omar is ignored and Dana is returned.
  2. 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.
  3. 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);
    }
}

How It Works

  1. User values survive. fontSize and theme already exist, so the defaults 14 and light are skipped and the calls return 18 and dark.
  2. Only the gap is filled. language is missing in settings, so en is stored and the call returns null, which bumps the counter.
  3. Unlike putAll. settings.putAll(defaults) would have overwritten the user's choices; looping with putIfAbsent merges in the other direction.

Frequently Asked Questions

The current value if the key already has a non-null value (and nothing changes), otherwise null after storing the new value.
Yes. A key mapped to null is treated as absent, so the new value is stored.
putIfAbsent takes a ready-made value that is always created; computeIfAbsent takes a function and calls it only when the key is missing.
No. TreeMap is not synchronized. Use ConcurrentSkipListMap for a sorted map with an atomic putIfAbsent.
Java 8, as a default method of Map. TreeMap got its own faster implementation in Java 15 with the same behaviour.

Next: putLast()

Java 21 SequencedMap method that a TreeMap always rejects.

putLast() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful