Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Map.computeIfAbsent: create a list on demand

Create a user's list only when it is needed, and reuse that same list on subsequent calls for the user's key.

Version: Java SE 21

Syntax

default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)

Map.computeIfAbsent is a default method of java.util.Map<K, V>, available since Java 8. If the key already has a non-null value, the method returns it without calling the mapping function. If the key is missing or maps to null, the method passes the key to the function, then stores and returns the result if it is non-null.

If the function returns null, the method returns null without inserting or removing anything: a missing key stays missing, and an existing mapping to null stays in place. An unchecked exception from the function propagates without storing a result. Do not modify the same map from inside the function. Passing null as the function causes NullPointerException. An unmodifiable map can reject the operation with UnsupportedOperationException, and whether a null key is allowed depends on the implementation.

In a Map<String, List<String>> of user tasks, a list is absent from the map until you store one. The lambda user -> new ArrayList<>() creates it on the first call that needs it. While that list remains mapped to the key, subsequent calls return the same object, not a copy. Call add on the returned list outside the lambda.

The default Map implementation guarantees neither synchronization nor atomicity. In ConcurrentHashMap, the computeIfAbsent call is atomic, but that does not make a later add on a shared ArrayList thread-safe.

Examples

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserTasks {
    public static void main(String[] args) {
        Map<String, List<String>> tasksByUser = new HashMap<>();
        System.out.println(tasksByUser.containsKey("ada"));

        List<String> first = tasksByUser.computeIfAbsent("ada", user -> new ArrayList<>());
        first.add("read");

        List<String> second = tasksByUser.computeIfAbsent("ada", user -> new ArrayList<>());
        second.add("review");

        System.out.println(first == second);
        System.out.println(tasksByUser.get("ada"));
    }
}

Result

false
true
[read, review]

The first line shows that `ada` is absent. On the second line, `true` means `first` and `second` refer to the same list object. The third line shows both tasks in that list.

Related lessons

  • Java · Lesson 39 · Intermediate · Version: 2

Sources