Java 25 (LTS) reference · Map and HashMap Methods

Java Map computeIfAbsent() Method

Return the value for a key, creating and storing it with a function first if the key is missing. Ideal for grouping.

Java 25 (LTS) Since Java 8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

map.computeIfAbsent(key, mappingFunction)

Parameters

ParameterDescription
key
K
The key.
mappingFunction
Function
Creates the value for a missing key.

Return value

The existing or new value.

Examples

Group words by length
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<Integer, List<String>> byLength = new TreeMap<>();
        for (String w : List.of("tea", "mug", "kettle", "cup")) {
            byLength.computeIfAbsent(w.length(), k -> new ArrayList<>()).add(w);
        }
        System.out.println(byLength);
    }
}

Output

{3=[tea, mug, cup], 6=[kettle]}

Run this on your computer — see “Get Started” for setup.

A tiny cache
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> cache = new HashMap<>();
        int[] calls = {0};
        for (String s : List.of("ab", "ab", "abc")) cache.computeIfAbsent(s, k -> { calls[0]++; return k.length(); });
        System.out.println(new TreeMap<>(cache) + ", computed " + calls[0] + " times");
    }
}

Output

{ab=2, abc=3}, computed 2 times

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 8Added

Was this page helpful?