Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
keyObjectThe key to remove.
valueObjectOptional: 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

In the tutorial

  • Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.

Thanks for reading!

Donate to the site — we work hard for you.