Library contents

Java Map.compute and Map.computeIfPresent

Recalculate a mapping from its previous value. computeIfPresent runs only for a key with a non-null value, while compute also handles a missing key.

A simple example

Map.compute and Map.computeIfPresent

  1. Start with A = 3
  2. Do this Subtract 1 for existing A
  3. Result A = 2
The update reads the old value before storing the calculated one.

Syntax

Java syntax
stock.computeIfPresent(key, (k, n) -> n - 1)
Run these examples in Java

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

java Main.java

Reduce only the stock that is on the ledger

A storeroom issues one mug and receives a request for an unlisted bowl. The clerk should reduce the mug balance but leave the unlisted product out of the ledger.

Result2
Main.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Main {
    public static void main(String[] args) throws Exception {
        var stock = new HashMap<>(Map.of("Mug", 3));
        for (String item : List.of("Mug", "Bowl")) {
            stock.computeIfPresent(item, (key, count) -> count - 1);
        }
        System.out.println(stock.get("Mug"));
    }
}
Output
2

The mug drops from three to two. The absent bowl has no value to recalculate.

Advertisements

Remove a locker entry when its balance reaches zero

A locker service records how many keys remain checked out for each room. When the last key for room A comes back, the entry should disappear from the outstanding-keys ledger.

Resultfalse
Main.java
import java.util.HashMap;
import java.util.Map;

class Main {
    public static void main(String[] args) throws Exception {
        var keys = new HashMap<>(Map.of("A", 1));
        keys.compute("A", (room, count) -> count == null || count <= 1 ? null : count - 1);
        System.out.println(keys.containsKey("A"));
    }
}
Output
false

The remapping function returns null for the final key, which removes room A.

Issue paintbrushes

A class has fourteen brushes under its art-room key. An existing stock record is reduced by the number handed out. What value is written back under the same key?

Given14 brushes − 3 issued
Worked result11

What to watch for

Returning null from the remapping function removes an existing mapping.

Documentation for Map.compute and Map.computeIfPresent