Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Map.compute: recompute the value for a key

Use `Map.compute` to apply the same function whether a key is present or absent. Return `null` from the function to remove the entry.

Version: Java SE 21

Syntax

default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

Map.compute is a default method on java.util.Map<K, V>, available since Java 8. In map.compute(key, (k, v) -> ...), the function runs whether the key is present or absent. It receives the supplied key as k and the current value as v.

The function receives v == null both when the key is absent and when it maps to null. If the distinction matters, use containsKey on a map that permits null values, such as HashMap. A non-null result is stored and returned by compute. A null result removes an existing entry or leaves an absent key absent; in either case, compute returns null.

By contrast, computeIfAbsent calls its function only when the key is absent or maps to null, and passes only the key. computeIfPresent passes both key and value, but calls its function only when the current value is non-null.

Do not modify the same map from inside the function. If the function throws an unchecked exception, compute propagates it and leaves the mapping unchanged. Passing null instead of a function throws NullPointerException, and a map that does not support the modification may throw UnsupportedOperationException. The default implementation does not guarantee atomicity; ConcurrentHashMap.compute makes the entire call atomic, so keep the function short.

Examples

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> counts = new HashMap<>();
        BiFunction<String, Integer, Integer> increment = (k, v) -> v == null ? 1 : v + 1;

        System.out.println(counts.compute("visits", increment));
        System.out.println(counts.compute("visits", increment));
        System.out.println(counts.compute("visits", (k, v) -> null));
        System.out.println(counts.containsKey("visits"));
    }
}

Result

1
2
null
false

The first call creates the `visits` counter at `1`, the second increments it to `2`, and the third removes the entry and returns `null`. The final `false` confirms that the key is absent, not mapped to `null`.

Related lessons

  • Java · Lesson 39 · Intermediate · Version: 2

Sources