HashMap<K, V> · Java

remove

Removes a key (optionally only if mapped to a given value).

public V remove(Object key); public boolean remove(Object key, Object value)

Complexity

ExpectedO(1)
Worst caseO(n), or O(log n) with tree bins
Extra spaceO(1)

Find the node in its bin and unlink it. The table does not shrink.

Tested example

Map<String, Integer> ages = new HashMap<>(Map.of("ada", 36, "bob", 25));
assert ages.remove("bob") == 25;
assert ages.remove("bob") == null; // missing: null, no exception
assert ages.remove("ada", 99) == false; // remove(key, value) only if it matches
assert ages.size() == 1;
Runs in the test suite on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/test/java/dev/bekadan/dsa/collections/HashMapExamples.java

Parameters

key
The key.

Behaviour

Returns
The removed value or null; the two-argument form returns whether it removed.
Errors and preconditions
None.
Changes
Unlinks one node.
Memory and invalidation
Does not shrink.