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
Call
What 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
Parameter
Description
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 Value
Description
V
remove(key): the previous value, or null if there was no mapping.
boolean
remove(key, value): true if the mapping was removed.