Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Map.computeIfPresent()

Changes the value for a key only if the key is already in the map.

Available since: Java 8

Syntax

default V computeIfPresent(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 and returns the new one; null removes the key.

Return value

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

Examples

A missing key is not added:

void main() {
    Map<String, Integer> prices = new TreeMap<>(Map.of("tea", 3, "coffee", 4));
    prices.computeIfPresent("tea", (k, v) -> v + 1);
    prices.computeIfPresent("juice", (k, v) -> v + 1);
    IO.println(prices);
}

Output:

{coffee=4, tea=4}

Decreasing a quantity in a cart and removing the item when it reaches zero:

void main() {
    Map<String, Integer> cart = new TreeMap<>(Map.of("pen", 1, "book", 2));
    cart.computeIfPresent("pen", (k, v) -> v > 1 ? v - 1 : null);
    cart.computeIfPresent("book", (k, v) -> v > 1 ? v - 1 : null);
    IO.println(cart);
}

Output:

{book=1}

Notes

Replaces the pair if (map.containsKey(key)) map.put(key, ...) with a single call. For a missing key the function is not called and the method returns null. If the key may be absent and must be created, use compute() or merge().

See also

  • Map.compute() — Computes a new value for a key from the old one (or from null if the key is absent).
  • 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.containsKey() — Checks whether a map has a key.

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.