Java HashMap computeIfPresent() Method

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

Definition

In Java, computeIfPresent(key, remappingFunction) runs the function only if key is in the map with a non-null value. The function receives the key and the old value, and its result replaces the old value.

If the function returns null, the mapping is removed. For a missing key, or a key mapped to null, nothing happens and the method returns null.

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. computeIfPresent was added in Java 8 as a default method of Map; HashMap overrides it.

Syntax

Pass the key and a lambda of (key, oldValue).

Java
Map<String, Integer> salary = new HashMap<>();
salary.put("Asha", 3000);
salary.computeIfPresent("Asha", (name, s) -> s + 500);   // 3500
salary.computeIfPresent("Zoe", (name, s) -> s + 500);    // null, not added
CallWhat it does
map.computeIfPresent(k, (key, v) -> v + 1)Increment an existing counter only.
map.computeIfPresent(k, (key, v) -> v > 1 ? v - 1 : null)Count down and remove at zero.
map.computeIfAbsent(k, f)The opposite case.
map.replace(k, v)Replace an existing value without a function.

Inside the function the old value is never null, so you can call methods on it without a null check.

Library declarations
Java
// java.util.HashMap<K, V> (Java 8+)
public V computeIfPresent(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 non-null value; returns the new value or null to remove. Must not be null.

Return Value

Return ValueDescription
VThe new value now stored for key.
nullThe key was absent or mapped to null, or the function returned null and the key was removed.

Compare with Similar Methods

Conditional updates:

MethodHow it differs
compute(k, f)Always runs, passing null for a missing key.
computeIfAbsent(k, f)Runs only for missing or null keys.
replace(k, v)Sets a fixed value if the key exists.
remove(k, v)Removes only on an exact value match.

Java Examples

Example 1 — Give a Raise Only to Existing Employees

Raise one employee's salary, and see that an unknown name is not added.

Java
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class HashMapComputeIfPresentDemo {
    public static void main(String[] args) {
        Map<String, Integer> salary = new HashMap<>();
        salary.put("Asha", 3000);
        salary.put("Ben", 2800);

        Integer a = salary.computeIfPresent("Asha", (name, s) -> s + 500);
        Integer z = salary.computeIfPresent("Zoe", (name, s) -> s + 500);

        System.out.println("Asha -> " + a);
        System.out.println("Zoe -> " + z + ", added? " + salary.containsKey("Zoe"));
        System.out.println(new TreeMap<>(salary));
    }
}

How It Works

  1. Key found. Asha is in the map with 3000, so the lambda runs and 3500 is stored and returned.
  2. Key not found. Zoe is not an employee, so the lambda never runs and the call returns null.
  3. No accidental insert. Unlike compute, there is no null case to handle, and Zoe is not added.
  4. Others untouched. Ben's salary is unchanged, as the sorted printout shows.

Example 2 — Lose a Life and Leave the Game at Zero

Each hit takes one life; returning null removes a player who has none left.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapComputeIfPresentLives {
    public static void main(String[] args) {
        Map<String, Integer> lives = new HashMap<>();
        lives.put("p1", 2);
        lives.put("p2", 1);

        String[] hits = {"p2", "p1", "p2", "p1"};
        for (String player : hits) {
            Integer left = lives.computeIfPresent(player, (k, v) -> v > 1 ? v - 1 : null);
            System.out.println(player + " hit, returned " + left + ", in game: " + lives.containsKey(player));
        }
        System.out.println("still playing: " + lives);
    }
}

How It Works

  1. Last life. p2 has 1 life, so v > 1 is false, the lambda returns null, and p2 is removed.
  2. One life left. p1 drops from 2 to 1 and stays in the game.
  3. Already gone. The second hit on p2 finds no key, so nothing runs; the return value is null just like a removal, which is why the loop also prints containsKey.
  4. Empty at the end. p1's second hit removes p1 too, and the map prints as {}.

Example 3 — A null Value Skips the Function

Format one draft using its key; a draft mapped to null is skipped instead of causing a NullPointerException.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapComputeIfPresentNull {
    public static void main(String[] args) {
        Map<String, String> drafts = new HashMap<>();
        drafts.put("intro", "hello");
        drafts.put("outro", null);

        String r1 = drafts.computeIfPresent("intro", (key, text) -> key + ": " + text.toUpperCase());
        String r2 = drafts.computeIfPresent("outro", (key, text) -> key + ": " + text.toUpperCase());

        System.out.println("intro -> " + r1);
        System.out.println("outro -> " + r2 + ", key kept? " + drafts.containsKey("outro"));
        System.out.println("outro value: " + drafts.get("outro"));
    }
}

How It Works

  1. Key in the result. The lambda's first parameter is the key, so the intro text becomes "intro: HELLO".
  2. null is not "present". outro exists but holds null, so the lambda is skipped; calling text.toUpperCase() on null would otherwise have thrown.
  3. Nothing removed. Skipping is not the same as returning null from the lambda: the outro key stays in the map.
  4. Value unchanged. get("outro") still returns null.

Frequently Asked Questions

If the key has a non-null value, it replaces that value with the function result, or removes the key if the result is null. Otherwise it does nothing.
Return null from the function. The mapping is removed.
No. It never adds a key; use compute() or computeIfAbsent() for that.
The function is not called and the key keeps its null value.
Java 8 added it to the Map interface.

Next: containsKey()

Check whether a key is present.

containsKey() 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.

11 people found this page helpful