Java TreeMap computeIfAbsent() Method

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

Definition

In Java, computeIfAbsent(key, function) looks up key. If the key is missing (or mapped to null), it calls function.apply(key), stores the result, and returns it. If the key already has a value, the function is not called and the existing value is returned.

This makes it perfect for "get the list for this key, creating it first if needed", and for caches where computing a value is slow. With a TreeMap the groups or cached items come out sorted by key.

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 a function that builds the value from the key.

Java
TreeMap<Integer, List<String>> byGrade = new TreeMap<>();
byGrade.computeIfAbsent(3, g -> new ArrayList<>()).add("Omar");
CallWhat it does
map.computeIfAbsent(k, x -> new ArrayList<>()).add(v)Group values under a key.
map.computeIfAbsent(k, x -> load(x))Cache: compute only on the first request.
map.computeIfAbsent(k, x -> null)Stores nothing; returns null.

Since the method returns the value in the map, you can chain .add(...) directly onto it.

Library declarations
Java
// java.util.TreeMap<K, V>
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)

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

Parameters

ParameterDescription
key (K)The key to look up. Not null under natural ordering.
mappingFunction (Function<? super K, ? extends V>)Builds the value from the key. Must not be null.

Return Value

Return ValueDescription
VThe existing value, or the newly computed one.
nullThe function returned null; nothing was stored.

Compare with Similar Methods

Creating values on demand:

MethodHow it differs
putIfAbsent(k, v)Takes a ready value that is always created.
compute(k, f)Runs for every key, absent or present.
getOrDefault(k, d)Returns a fallback without storing it.
HashMap.computeIfAbsentSame pattern with unordered keys.

Java Examples

Example 1 — Group Pupils by Grade Level

Each record is "name:grade". Build a sorted map from grade to the list of names.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

public class TreeMapComputeIfAbsentGroups {
    public static void main(String[] args) {
        String[] pupils = {"Omar:3", "Lily:1", "Ben:3", "Zara:2", "Ava:1"};
        TreeMap<Integer, List<String>> byGrade = new TreeMap<>();
        for (String p : pupils) {
            String[] parts = p.split(":");
            int grade = Integer.parseInt(parts[1]);
            byGrade.computeIfAbsent(grade, g -> new ArrayList<>()).add(parts[0]);
        }
        System.out.println(byGrade);
        System.out.println("grades: " + byGrade.size());
    }
}

How It Works

  1. A list per new grade. The first pupil in grades 3, 1, and 2 triggers new ArrayList<>(); that list is stored and returned.
  2. Later pupils reuse it. For Ben (grade 3) and Ava (grade 1) the list already exists, so the function is skipped and the name is appended to it.
  3. Grades in numeric order. The map prints 1, 2, 3, while each list keeps the order the names arrived in.

Example 2 — Cache Slow Lookups and Count Them

The lookup function counts how often it runs; repeated codes are served from the map.

Java
import java.util.TreeMap;

public class TreeMapComputeIfAbsentCache {
    static int lookups = 0;

    static String slowLookup(String code) {
        lookups++;
        return "Airport " + code;
    }

    public static void main(String[] args) {
        TreeMap<String, String> cache = new TreeMap<>();
        String[] requests = {"LHR", "CDG", "LHR", "LHR", "AMS"};
        for (String code : requests) {
            cache.computeIfAbsent(code, c -> slowLookup(c));
        }
        System.out.println(cache);
        System.out.println("requests: " + requests.length + ", slow lookups: " + lookups);
    }
}

How It Works

  1. Three distinct codes. LHR, CDG, and AMS are each missing on first request, so slowLookup runs three times.
  2. Hits skip the function. The second and third LHR requests find a value, so the lambda is never invoked and lookups stays at 3.
  3. A sorted cache. The cached airports print as AMS, CDG, LHR, handy when the cache is shown in a report.

Example 3 — Skip Inputs the Function Cannot Handle

Store square roots of perfect squares; for a negative input the function returns null.

Java
import java.util.TreeMap;

public class TreeMapComputeIfAbsentNull {
    public static void main(String[] args) {
        TreeMap<String, Integer> roots = new TreeMap<>();
        String[] inputs = {"49", "-4", "16"};
        for (String s : inputs) {
            Integer r = roots.computeIfAbsent(s, k -> {
                int n = Integer.parseInt(k);
                return n < 0 ? null : (int) Math.sqrt(n);
            });
            System.out.println(s + " -> " + r);
        }
        System.out.println(roots);
    }
}

How It Works

  1. Perfect squares are stored. Math.sqrt(49) is exactly 7.0 and Math.sqrt(16) is 4.0, so the casts give 7 and 4.
  2. null means "no entry". For "-4" the lambda returns null; computeIfAbsent returns null and does not add the key.
  3. String keys sort as text. "16" comes before "49" because the comparison is character by character ('1' < '4'), not numeric.

Frequently Asked Questions

Only when the key is missing or mapped to null. Otherwise it returns the existing value without calling the function.
Use map.computeIfAbsent(key, k -> new ArrayList<>()).add(value). The groups come out sorted by key.
Nothing is stored and computeIfAbsent returns null.
When creating the value costs something, yes: putIfAbsent builds the value every time, computeIfAbsent only when it is needed.
No. On Java 15 and later TreeMap detects it and throws ConcurrentModificationException; on older versions the result is unpredictable.

Next: computeIfPresent()

Update or drop a value only when the key exists.

computeIfPresent() 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.

13 people found this page helpful