In Java, compute(key, remappingFunction) calls the function with the key and its current value, or null if the key is missing. Whatever the function returns becomes the key's new value, and compute returns it.
If the function returns null, the mapping is removed (or simply not created). That one rule lets a single call add, update, or delete, which makes compute the most general of the update methods.
An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety. compute was added in Java 8 as a default method of Map; HashMap overrides it with a single bucket lookup.
Syntax
Pass the key and a lambda of (key, oldValue).
Java
Map<String, Integer> hits = new HashMap<>();
hits.compute("home", (k, v) -> v == null ? 1 : v + 1); // 1
hits.compute("home", (k, v) -> v == null ? 1 : v + 1); // 2
hits.compute("home", (k, v) -> null); // removed
Call
What it does
map.compute(k, (key, v) -> v == null ? 1 : v + 1)
Counter that also handles the first time.
map.compute(k, (key, v) -> null)
Removes k.
map.computeIfAbsent(k, f)
Runs only for missing keys.
map.computeIfPresent(k, f)
Runs only for present, non-null values.
The function always runs, even for a missing key, so it must handle v == null. Forgetting that check causes a NullPointerException on the first call.
Library declarations
Java
// java.util.HashMap<K, V> (Java 8+)
public V compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction)
// Default method in Map<K, V>, overridden by HashMap
Parameters
Parameter
Description
key (K)
The key to update.
remappingFunction
Receives the key and its current value (or null); returns the new value, or null to remove. Must not be null.
Return Value
Return Value
Description
V
The new value now stored for key.
null
The function returned null; the key is not in the map.
One lambda handles both the first hit (value is null) and every later hit.
Java
import java.util.HashMap;
import java.util.Map;
public class HashMapComputeDemo {
public static void main(String[] args) {
String[] clicks = {"home", "shop", "home", "cart", "home", "shop"};
Map<String, Integer> hits = new HashMap<>();
for (String page : clicks) {
hits.compute(page, (k, v) -> v == null ? 1 : v + 1);
}
System.out.println(hits);
System.out.println("home: " + hits.get("home"));
}
}
Output
{shop=2, cart=1, home=3}
home: 3
HashMap iteration order is not guaranteed. This is the typical output on OpenJDK 8–21; other JDKs or versions may print the entries in a different order.
How It Works
First visit. When a page is seen for the first time, v is null, so the lambda returns 1 and a new mapping is created.
Later visits. For a page already in the map, v is its count, and v + 1 becomes the new value.
Totals. home appears three times, shop twice, and cart once.
Printed order. The map prints in table order (shop, cart, home here), which is not the order of the clicks.
Example 2 — Collect Guest Names per Room
Append each guest to a comma-separated list and print what compute returns each time.
Java
import java.util.HashMap;
import java.util.Map;
public class HashMapComputeAppend {
public static void main(String[] args) {
String[][] checkins = {{"R1", "Ana"}, {"R2", "Bo"}, {"R1", "Cy"}};
Map<String, String> rooms = new HashMap<>();
for (String[] c : checkins) {
String result = rooms.compute(c[0], (room, guests) -> guests == null ? c[1] : guests + ", " + c[1]);
System.out.println(c[0] + " -> " + result);
}
System.out.println("rooms used: " + rooms.size());
}
}
Output
R1 -> Ana
R2 -> Bo
R1 -> Ana, Cy
rooms used: 2
How It Works
Captured variable. The lambda uses c, the loop variable of an enhanced for, which is effectively final in each pass and therefore allowed.
Empty room. R1 starts with no guests, so guests is null and the result is just "Ana".
Append. On Cy's check-in, R1 already holds "Ana", so the lambda returns "Ana, Cy".
Return value.compute returns the value it stored, which the loop prints directly without calling get.
Example 3 — Update, Remove, Add, or Do Nothing
Four compute calls on a stock map show every combination of present/missing key and value/null result.
Java
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class HashMapComputeOutcomes {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("pens", 1);
stock.put("pads", 4);
Integer a = stock.compute("pads", (k, v) -> v - 1);
Integer b = stock.compute("pens", (k, v) -> v - 1 == 0 ? null : v - 1);
Integer c = stock.compute("ink", (k, v) -> v == null ? 10 : v + 10);
Integer d = stock.compute("glue", (k, v) -> null);
System.out.println("pads -> " + a + ", pens -> " + b + ", ink -> " + c + ", glue -> " + d);
System.out.println("pens present? " + stock.containsKey("pens") + ", glue present? " + stock.containsKey("glue"));
System.out.println(new TreeMap<>(stock));
}
}
Present, new value. pads had 4; the lambda returns 3, which replaces the old count.
Present, null result. pens drops to 0, so the lambda returns null and compute deletes the pens mapping.
Missing, new value. ink is not stored, v is null, and the returned 10 creates a new mapping.
Missing, null result. glue is missing and the lambda returns null, so nothing is added and compute returns null.
Frequently Asked Questions
It calls your function with the key and its current value (null if missing), stores the result as the new value, and removes the key if the result is null.
map.compute(key, (k, v) -> v == null ? 1 : v + 1). merge(key, 1, Integer::sum) is a shorter equivalent.
Return null from the function. The mapping is removed and compute() returns null.
compute() always runs the function, passing null for a missing key. computeIfPresent() runs only when the key has a non-null value.
No. Changing the map from inside the function is not allowed; HashMap throws ConcurrentModificationException in Java 9 and later.