Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Map.compute()

Computes a new value for a key from the old one (or from null if the key is absent).

Available since: Java 8

Syntax

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

Parameters

ParameterTypeDescription
keyKThe key.
remappingFunctionBiFunction<? super K, ? super V, ? extends V>Receives the key and the current value (null if absent) and returns the new one; null removes the key.

Return value

VThe new value, or null if the key was removed.

Examples

A word counter: for a new key v is null:

void main() {
    Map<String, Integer> counts = new TreeMap<>();
    for (String w : List.of("a", "b", "a", "c", "a")) {
        counts.compute(w, (k, v) -> v == null ? 1 : v + 1);
    }
    IO.println(counts);
}

Output:

{a=3, b=1, c=1}

If the function returns null, the key is removed:

void main() {
    Map<String, Integer> stock = new HashMap<>(Map.of("apple", 1, "pear", 5));
    stock.compute("apple", (k, v) -> v - 1 == 0 ? null : v - 1);
    IO.println(stock);
}

Output:

{pear=5}

Notes

compute() is the most general of the three methods: computeIfAbsent() calls the function only for a missing key, computeIfPresent() only for an existing one. For counting, merge(w, 1, Integer::sum) is shorter. The function must not modify the same map.

See also

  • Map.computeIfPresent() — Changes the value for a key only if the key is already in the map.
  • Map.computeIfAbsent() — Returns the value for a key, creating it with a function if the key is absent.
  • Map.merge() — Adds a value under a key or combines it with the existing one.
  • Map.put() — Stores a value under a key, replacing the old one.

In the tutorial

  • Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.

Thanks for reading!

Donate to the site — we work hard for you.