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
- Start with A = 3
- Do this Subtract 1 for existing A
- Result A = 2
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.javaReduce 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.
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"));
}
}
2
The mug drops from three to two. The absent bowl has no value to recalculate.
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.
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"));
}
}
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?
What to watch for
Returning null from the remapping function removes an existing mapping.