Library contents

Java Map.computeIfAbsent

Create a value on demand for a missing key or a key mapped to null. Return the stored value so the caller can use it immediately.

A simple example

Map.computeIfAbsent

  1. Start with A already holds [1]
  2. Do this Append 2 in the A group
  3. Result A holds [1, 2]
The map locates the group and its list stores both values.

Syntax

Java syntax
groups.computeIfAbsent(key, k -> new ArrayList<>())
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Group two parcels on one delivery route

A small courier sorts parcels into a list for each route. The first North parcel needs a new list, while the next North parcel should join that same list without erasing the first one.

ResultP2, P8
Main.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

class Main {
    public static void main(String[] args) throws Exception {
        var routes = new HashMap<String, List<String>>();
        for (String parcel : List.of("P2", "P8")) {
            routes.computeIfAbsent("North", k -> new ArrayList<>()).add(parcel);
        }
        System.out.println(String.join(", ", routes.get("North")));
    }
}
Output
P2, P8

The list is created on the first lookup and reused when P8 arrives.

Advertisements

Leave an unknown depot out of the cache

A delivery clerk enters a depot code that the directory cannot resolve. The cache should stay empty so the directory can try again after the depot list is corrected.

Result0
Main.java
import java.util.HashMap;

class Main {
    public static void main(String[] args) throws Exception {
        var cache = new HashMap<String, String>();
        cache.computeIfAbsent("X9", code -> null);
        System.out.println(cache.size());
    }
}
Output
0

A null result leaves the absent key absent.

Fill the east-studio tote

A courier sorts parcels into destination totes as the labels arrive. Append each parcel to the list for its destination. In what order do the parcels appear in the selected group?

GivenEast P4 · West P8 · East P2
Worked resultP4 · P2

What to watch for

A null result from the mapping function installs no new value. Keep the function from modifying the same map.

Documentation for Map.computeIfAbsent