Java TreeMap remove() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.TreeMap

Definition

In Java, remove(key) deletes the mapping for key from a TreeMap and returns the value that was stored, or null if the key was not present. The tree rebalances itself afterwards, so the operation takes O(log n) time.

Since Java 8, Map also offers remove(Object key, Object value), which deletes the mapping only if the key is currently mapped to that value and returns a boolean. As with lookups, the key is matched by the map's comparator, not by equals.

An instance method of java.util.TreeMap, part of TreeMap since Java 1.2. 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.

Syntax

Remove by key, or by key and expected value.

Java
TreeMap<String, Integer> cart = new TreeMap<>();
cart.put("bread", 1);
Integer old = cart.remove("bread");          // 1
boolean ok = cart.remove("milk", 2);         // false: no such mapping
CallWhat it does
map.remove(k)Deletes k; returns the old value or null.
map.remove(k, v)Deletes only if k maps to v; returns true/false.
map.keySet().removeIf(p)Deletes every key that matches a condition.

A null result is ambiguous when the map stores null values: it can mean "removed a null value" or "key not found". Call containsKey() first if the difference matters.

Library declarations
Java
// java.util.TreeMap<K, V>
public V remove(Object key)

// Inherited from Map<K, V> (Java 8)
default boolean remove(Object key, Object value)

Parameters

ParameterDescription
key (Object)The key whose mapping should be deleted.
value (Object)Two-argument form only: the value the key must currently have.

Return Value

Return ValueDescription
Vremove(key): the previous value, or null if there was no mapping.
booleanremove(key, value): true if the mapping was removed.

Compare with Similar Methods

Ways to delete from a TreeMap:

MethodHow it differs
clear()Removes every mapping at once.
pollFirstEntry()Removes the lowest key and returns its entry.
computeIfPresent(k, f)Removes when the function returns null.
HashMap.remove(k)Same contract, hash-based lookup.

Java Examples

Example 1 — Take Items Out of a Shopping Cart

remove hands back the quantity it deleted, or null for an item that was never there.

Java
import java.util.TreeMap;

public class TreeMapRemoveCart {
    public static void main(String[] args) {
        TreeMap<String, Integer> cart = new TreeMap<>();
        cart.put("apple", 3);
        cart.put("bread", 1);
        cart.put("milk", 2);

        Integer gone = cart.remove("bread");
        System.out.println("removed bread, quantity was " + gone);
        System.out.println("remove eggs: " + cart.remove("eggs"));
        System.out.println("cart: " + cart);
    }
}

How It Works

  1. The deleted value comes back. remove("bread") returns 1, so the program can report what it just took out.
  2. A missing key is harmless. "eggs" was never added; the call changes nothing and returns null instead of throwing.
  3. Order is kept for the rest. The remaining items still print alphabetically: apple, then milk.

Example 2 — Cancel a Seat Only for Its Holder

remove(key, value) deletes the booking only when the seat really belongs to that person.

Java
import java.util.TreeMap;

public class TreeMapRemoveKeyValue {
    public static void main(String[] args) {
        TreeMap<Integer, String> seats = new TreeMap<>();
        seats.put(12, "Ravi");
        seats.put(14, "Mia");

        System.out.println("cancel 12 for Mia: " + seats.remove(12, "Mia"));
        System.out.println("cancel 12 for Ravi: " + seats.remove(12, "Ravi"));
        System.out.println("seats: " + seats);
    }
}

How It Works

  1. Wrong holder, no change. Seat 12 belongs to Ravi, so remove(12, "Mia") leaves it alone and returns false.
  2. Right holder, removed. The value matches with equals, the mapping is deleted, and the call returns true.
  3. A check-and-remove in one call. This replaces the pattern "if get(12) equals Ravi then remove(12)" with a single method, available since Java 8.

Example 3 — Remove a Tag Regardless of Case

A case-insensitive map removes "Java" when asked for "JAVA", but still rejects a null key.

Java
import java.util.TreeMap;

public class TreeMapRemoveIgnoreCase {
    public static void main(String[] args) {
        TreeMap<String, String> tags = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        tags.put("Java", "language");
        tags.put("SQL", "query");

        System.out.println("remove JAVA: " + tags.remove("JAVA"));
        System.out.println("tags: " + tags);
        try {
            tags.remove(null);
        } catch (NullPointerException e) {
            System.out.println("remove(null): " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Matched by the comparator. "JAVA" compares equal to "Java" under CASE_INSENSITIVE_ORDER, so that mapping is found and its value "language" returned.
  2. Only one tag left. The map now contains just SQL.
  3. This comparator does not accept null. CASE_INSENSITIVE_ORDER cannot compare null with "SQL", so remove(null) throws NullPointerException.

Frequently Asked Questions

The value that was mapped to the key, or null if the key was not in the map (or was mapped to null).
Added to Map in Java 8, it removes the mapping only if the key is currently mapped to that value and returns true when it did.
No. It returns null and leaves the map unchanged.
Not with natural ordering: it throws NullPointerException. Only a comparator that handles null allows it.
O(log n): the key is found by walking the tree, and the red-black tree rebalances after the deletion.

Next: replace()

Change the value of an existing key; never adds a key.

replace() 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