Map.remove()
Removes a pair by its key.
Available since: Java 1.2
Syntax
V remove(Object key)
default boolean remove(Object key, Object value)Parameters
| Parameter | Type | Description |
|---|---|---|
| key | Object | The key to remove. |
| value | Object | Optional: remove only if the value matches. |
Return value
V | booleanThe removed value (or `null`); the two-argument version returns `true` if the pair was removed.
Examples
Removing by key:
void main() {
Map<String, Integer> cart = new TreeMap<>(Map.of("tea", 2, "milk", 1, "bread", 1));
IO.println(cart.remove("milk"));
IO.println(cart.remove("juice"));
IO.println(cart);
}Output:
1
null
{bread=1, tea=2}Removing by a condition via entrySet():
void main() {
Map<String, Integer> cart = new TreeMap<>(Map.of("tea", 2, "milk", 0, "bread", 0));
cart.entrySet().removeIf(e -> e.getValue() == 0);
IO.println(cart);
}Output:
{tea=2}Notes
Do not call map.remove() inside a for loop over the same map — it causes ConcurrentModificationException. To remove by a condition use map.entrySet().removeIf(...) or map.values().removeIf(...).
See also
- Map.put() — Stores a value under a key, replacing the old one.
- Collection.removeIf() — Removes all collection elements that match a condition.
- Map.keySet() — Returns the set of all keys of a map.
In the tutorial
- Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.