In Java, compute(key, function) calls function.apply(key, oldValue), where oldValue is the current value or null if the key is missing. Whatever the function returns becomes the new value for key.
If the function returns null, an existing key is removed (and a missing key stays missing). Because the function sees both cases, compute can add, update, or delete in one call; you just have to handle oldValue == null yourself.
An instance method of java.util.TreeMap, added in Java 8 as part of the Map interface. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe. TreeMap has its own implementation since Java 15 (earlier versions use the Map default); the behaviour is the same.
Syntax
Pass the key and a lambda of the key and the old value.
Java
TreeMap<String, Integer> best = new TreeMap<>();
best.compute("Lea", (name, old) -> old == null ? 72 : Math.max(old, 72));
Call
What it does
map.compute(k, (key, old) -> old == null ? 1 : old + 1)
Counter that handles the first time itself.
map.compute(k, (key, old) -> null)
Removes k if present.
map.compute(k, (key, old) -> f(key))
Value derived from the key alone.
If the function throws an exception, it is passed on to you and the mapping is left exactly as it was.
Library declarations
Java
// java.util.TreeMap<K, V>
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
// Default method of Map<K, V> since Java 8; TreeMap overrides it since Java 15
Parameters
Parameter
Description
key (K)
The key to compute. Not null under natural ordering.
remappingFunction
BiFunction of the key and the current value (or null). Must not be null.
Return Value
Return Value
Description
V
The new value now stored for the key.
null
The function returned null; the key is absent afterwards.
Students take the quiz more than once; keep the highest score per name.
Java
import java.util.TreeMap;
public class TreeMapComputeBestScore {
public static void main(String[] args) {
String[] names = {"Lea", "Max", "Lea", "Ida", "Max"};
int[] scores = {72, 65, 88, 91, 60};
TreeMap<String, Integer> best = new TreeMap<>();
for (int i = 0; i < names.length; i++) {
int s = scores[i];
best.compute(names[i], (name, old) -> old == null ? s : Math.max(old, s));
}
System.out.println(best);
System.out.println("attempts: " + names.length + ", students: " + best.size());
}
}
Output
{Ida=91, Lea=88, Max=65}
attempts: 5, students: 3
How It Works
Both cases in one lambda. For a first attempt old is null and the score itself is stored; later attempts keep Math.max(old, s).
Higher and lower retries. Lea improves from 72 to 88, while Max's 60 is lower than his 65, so 65 stays.
Effectively final copy.s is a fresh local in each loop pass, which is why the lambda may capture it; the results print by name.
Example 2 — Return Library Copies and Drop Titles at Zero
Each return lowers the count; when the last copy comes back, the title leaves the "on loan" map.
Java
import java.util.TreeMap;
public class TreeMapComputeLoans {
public static void main(String[] args) {
TreeMap<String, Integer> onLoan = new TreeMap<>();
onLoan.put("Dune", 2);
onLoan.put("Emma", 1);
Integer dune = onLoan.compute("Dune", (title, n) -> n == null || n == 1 ? null : n - 1);
Integer emma = onLoan.compute("Emma", (title, n) -> n == null || n == 1 ? null : n - 1);
Integer gone = onLoan.compute("Ulysses", (title, n) -> n == null || n == 1 ? null : n - 1);
System.out.println("Dune: " + dune + ", Emma: " + emma + ", Ulysses: " + gone);
System.out.println(onLoan);
}
}
Output
Dune: 1, Emma: null, Ulysses: null
{Dune=1}
How It Works
Dune goes from 2 to 1. The old count is neither null nor 1, so the lambda returns 1 and compute stores it.
Emma's last copy removes the key. With 1 on loan the lambda returns null, and compute deletes Emma from the map.
Unknown title stays unknown. Ulysses was never borrowed: the lambda sees null, returns null, and nothing is added.
Example 3 — A Failing Function Leaves the Map Unchanged
Region totals are updated from text input; one input is not a number.
Java
import java.util.TreeMap;
public class TreeMapComputeParse {
public static void main(String[] args) {
TreeMap<String, Integer> totals = new TreeMap<>();
totals.put("north", 10);
String[] regions = {"north", "south", "north"};
String[] inputs = {"5", "7", "x9"};
for (int i = 0; i < regions.length; i++) {
String raw = inputs[i];
try {
totals.compute(regions[i], (region, sum) -> (sum == null ? 0 : sum) + Integer.parseInt(raw));
} catch (NumberFormatException e) {
System.out.println("skipped bad input for " + regions[i]);
}
}
System.out.println(totals);
}
}
Output
skipped bad input for north
{north=15, south=7}
How It Works
Two good inputs. north becomes 10 + 5 = 15, and south starts from 0 because its old value is null, ending at 7.
The third call throws.Integer.parseInt("x9") throws NumberFormatException inside the lambda, and compute passes it straight to the catch.
No half-done update. Since the function never returned a value, north keeps 15; the map is updated only after a successful result.
Frequently Asked Questions
The new value stored for the key, or null if the function returned null (in which case the key is removed or stays absent).
null. Your function must handle that case, for example old == null ? 1 : old + 1.
Return null from the function. An existing key is deleted; a missing key is simply not added.
The exception propagates to the caller and the map is left unchanged.
For counters and joins, merge is shorter because it never passes null and takes the new value directly. Use compute when the result depends on the key or needs custom null handling.