Java HashMap compute() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

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
CallWhat 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

ParameterDescription
key (K)The key to update.
remappingFunctionReceives the key and its current value (or null); returns the new value, or null to remove. Must not be null.

Return Value

Return ValueDescription
VThe new value now stored for key.
nullThe function returned null; the key is not in the map.

Compare with Similar Methods

The compute family:

MethodHow it differs
computeIfAbsent(k, f)Only for missing (or null) keys; never removes.
computeIfPresent(k, f)Only for keys with a non-null value.
merge(k, v, f)Combines a given value with the old one; shorter for counters.
replaceAll(f)Updates every key at once.

Java Examples

Example 1 — Count Page Hits with compute()

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"));
    }
}

How It Works

  1. 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.
  2. Later visits. For a page already in the map, v is its count, and v + 1 becomes the new value.
  3. Totals. home appears three times, shop twice, and cart once.
  4. 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());
    }
}

How It Works

  1. Captured variable. The lambda uses c, the loop variable of an enhanced for, which is effectively final in each pass and therefore allowed.
  2. Empty room. R1 starts with no guests, so guests is null and the result is just "Ana".
  3. Append. On Cy's check-in, R1 already holds "Ana", so the lambda returns "Ana, Cy".
  4. 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));
    }
}

How It Works

  1. Present, new value. pads had 4; the lambda returns 3, which replaces the old count.
  2. Present, null result. pens drops to 0, so the lambda returns null and compute deletes the pens mapping.
  3. Missing, new value. ink is not stored, v is null, and the returned 10 creates a new mapping.
  4. 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.

Next: computeIfAbsent()

Create and store a value only when the key is missing.

computeIfAbsent() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful