Java TreeMap computeIfPresent() Method

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

Definition

In Java, computeIfPresent(key, function) does something only when key exists in the TreeMap with a non-null value. It then calls function.apply(key, oldValue) and stores the result.

If the function returns null, the key is removed. For a missing key (or one mapped to null) the function is not called, nothing changes, and the method returns null.

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 existing value.

Java
TreeMap<String, Integer> balances = new TreeMap<>();
balances.computeIfPresent("ACC-2", (id, owed) -> owed + 15);   // only if ACC-2 exists
CallWhat it does
map.computeIfPresent(k, (key, v) -> v + 1)Updates an existing value.
map.computeIfPresent(k, (key, v) -> v > 1 ? v - 1 : null)Decrements and removes at the end.
map.computeIfPresent(missing, f)Returns null; f is not called.

It replaces the pattern "if (map.containsKey(k)) map.put(k, f(map.get(k)));" with one tree search.

Library declarations
Java
// java.util.TreeMap<K, V>
public V computeIfPresent(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

ParameterDescription
key (K)The key to update. Not null under natural ordering.
remappingFunctionBiFunction of the key and the existing non-null value. Must not be null.

Return Value

Return ValueDescription
VThe new value stored for the 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
computeIfAbsent(k, f)The opposite: runs only for missing keys.
replace(k, v)Sets a fixed value for an existing key.
compute(k, f)Runs for every key and may add one.
HashMap.computeIfPresentSame rules, no ordering.

Java Examples

Example 1 — Add a Late Fee Only to Existing Accounts

A list of late account IDs contains one that does not exist.

Java
import java.util.TreeMap;

public class TreeMapComputeIfPresentFee {
    public static void main(String[] args) {
        TreeMap<String, Integer> balances = new TreeMap<>();
        balances.put("ACC-7", 120);
        balances.put("ACC-2", 40);

        String[] late = {"ACC-2", "ACC-9"};
        for (String acc : late) {
            Integer result = balances.computeIfPresent(acc, (id, owed) -> owed + 15);
            System.out.println(acc + ": " + result);
        }
        System.out.println(balances);
    }
}

How It Works

  1. ACC-2 is charged. It exists with 40, so the lambda returns 55, which is stored and printed.
  2. ACC-9 is not created. No such account exists, so the lambda is skipped and the result is null; no new balance appears.
  3. IDs in text order. ACC-2 prints before ACC-7 because the keys are compared as strings, character by character.

Example 2 — Take Sold-Out Shows Off the List

Sell one seat for each show; a show with one seat left disappears.

Java
import java.util.TreeMap;

public class TreeMapComputeIfPresentSoldOut {
    public static void main(String[] args) {
        TreeMap<String, Integer> seats = new TreeMap<>();
        seats.put("10:00 show", 1);
        seats.put("18:30 show", 3);

        seats.computeIfPresent("10:00 show", (show, left) -> left > 1 ? left - 1 : null);
        seats.computeIfPresent("18:30 show", (show, left) -> left > 1 ? left - 1 : null);
        System.out.println("open shows: " + seats);
        System.out.println("10:00 still listed? " + seats.containsKey("10:00 show"));
    }
}

How It Works

  1. Last seat sold. The 10:00 show has 1 seat, so the lambda returns null and the show is removed from the map.
  2. Evening show decremented. 18:30 has 3 seats; the lambda returns 2, which replaces the old count.
  3. Removal confirmed. containsKey now reports false for the morning show, so it no longer appears in listings.

Example 3 — A Key Mapped to null Is Treated as Absent

Susan has no nickname yet (null). The function is not called for her.

Java
import java.util.TreeMap;

public class TreeMapComputeIfPresentNullValue {
    public static void main(String[] args) {
        TreeMap<String, String> nicknames = new TreeMap<>();
        nicknames.put("Robert", "Rob");
        nicknames.put("Susan", null);

        String a = nicknames.computeIfPresent("Robert", (name, nick) -> nick + "bie");
        String b = nicknames.computeIfPresent("Susan", (name, nick) -> "Sue");

        System.out.println("Robert -> " + a);
        System.out.println("Susan -> " + b);
        System.out.println(nicknames);
    }
}

How It Works

  1. Rob becomes Robbie. Robert has a non-null value, so the lambda appends "bie" and the result is stored.
  2. Susan is skipped. Her key exists but its value is null, which counts as absent; "Sue" is never computed and the call returns null.
  3. The null stays. The map still shows Susan=null; use put or compute to fill such a value.

Frequently Asked Questions

No. If the key is missing, the function is not called, nothing is added, and the method returns null.
Return null from the function. The key is then removed from the TreeMap.
It is treated as absent: the function is not called and the null value stays.
replace stores a fixed value; computeIfPresent calculates the new value from the old one and can remove the key.
Java 8, as a Map default method. TreeMap has its own implementation since Java 15.

Next: containsKey()

Check whether a key is present in O(log n) time.

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.

14 people found this page helpful