Remove Entries from a Map
A map can lose entries by key, by key and value together, by a condition on keys or values, by key range, or automatically when it gets too large. Most of these go through the map's keySet, values and entrySet views. This page explains how removal works, shows each approach with its return values, reproduces the loop trap, and measures the bulk options.
Contents
How removal works in a map Remove by key, and by key and value Remove by condition through the views The loop trap Removal through compute, ranges and eviction Maps that refuse removal, and keys that cannot be found A HashMap does not shrink after removal How fast is each approach? Which approach to use
How removal works in a map
A map has no positions, so entries are removed by key, either directly with remove(key)keySet()values()entrySet()removeremoveIfremoveAllretainAll
In a HashMapTreeMap
| Code | Since | Removes | Best for |
|---|---|---|---|
map.remove(key) | Java 1.2 | One entry; returns its old value | A known key |
map.remove(key, value) | Java 8 | The entry only if it has that value | Conditional removal, concurrent maps |
values().removeIf(...) | Java 8 | Entries whose value matches | Conditions on values |
entrySet().removeIf(...) | Java 8 | Entries matching a key-and-value condition | Conditions on both |
keySet().removeAll(keys) | Java 1.2 | All listed keys | A batch of keys |
Iterator.remove() | Java 1.2 | The current entry | Loops with extra work per entry |
computecomputeIfPresentmergenull | Java 8 | The entry being updated | Counters that reach zero |
headMaptailMapsubMapclear() | Java 1.2 | A key range of a sorted map | Expiring old keys |
removeEldestEntry | Java 1.4 | The oldest entry, automatically | Size-limited caches |
Every example on this page was compiled and run on JDK 21, and each program creates its own small map, so it can be pasted and run on its own.
Remove by key, and by key and value
The stock map has one entry with value 0, and a second map holds a nullremove
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class RemoveByKey {
public static void main(String[] args) {
Map<String, Integer> stock = new TreeMap<>(Map.of("apple", 5, "pear", 0, "plum", 3));
Integer old = stock.remove("pear"); // returns the old value
System.out.println("remove(pear) -> " + old + " " + stock);
System.out.println("remove(kiwi) -> " + stock.remove("kiwi"));
// remove(key, value): only if the key currently maps to that value
System.out.println("remove(apple, 9) -> " + stock.remove("apple", 9));
System.out.println("remove(apple, 5) -> " + stock.remove("apple", 5) + " " + stock);
// A null return can mean "absent" OR "the value was null"
Map<String, String> notes = new HashMap<>();
notes.put("x", null);
System.out.println("remove(x) -> " + notes.remove("x"));
System.out.println("remove(y) -> " + notes.remove("y"));
}
}
Output:
remove(pear) -> 0 {apple=5, plum=3}
remove(kiwi) -> null
remove(apple, 9) -> false
remove(apple, 5) -> true {plum=3}
remove(x) -> null
remove(y) -> null
returns the value the key had, 0 forremove(key) , orpear if the key was absent.null removes only when the key currently maps to that value:remove(key, value) with 9 stayed, with 5 it was removed. On aapple this check and removal happen atomically.ConcurrentHashMap- When a map can hold
values,null returnsremove both for a key mapped tonull and for a missing key, asnull andx show. Checky first if the difference matters.containsKey
Remove by condition through the views
A fresh copy of the same map is used for each approach, so every result starts from five fruits with two zero quantities.
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class RemoveByCondition {
static Map<String, Integer> fresh() {
return new TreeMap<>(Map.of("apple", 5, "pear", 0, "plum", 3, "fig", 0, "kiwi", 8));
}
public static void main(String[] args) {
// By value: removeIf on values()
Map<String, Integer> a = fresh();
a.values().removeIf(qty -> qty == 0);
System.out.println("values().removeIf qty==0: " + a);
// By key and value together: removeIf on entrySet()
Map<String, Integer> b = fresh();
b.entrySet().removeIf(e -> e.getKey().startsWith("p") && e.getValue() < 5);
System.out.println("entrySet().removeIf: " + b);
// A set of keys: removeAll on keySet()
Map<String, Integer> c = fresh();
c.keySet().removeAll(Set.of("apple", "kiwi"));
System.out.println("keySet().removeAll: " + c);
// Explicit iterator, when the loop does more than decide
Map<String, Integer> d = fresh();
Iterator<Map.Entry<String, Integer>> it = d.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Integer> e = it.next();
if (e.getValue() == 0) {
System.out.println(" dropping " + e.getKey());
it.remove();
}
}
System.out.println("iterator.remove: " + d);
}
}
Output:
values().removeIf qty==0: {apple=5, kiwi=8, plum=3}
entrySet().removeIf: {apple=5, fig=0, kiwi=8}
keySet().removeAll: {fig=0, pear=0, plum=3}
dropping fig
dropping pear
iterator.remove: {apple=5, kiwi=8, plum=3}
removed both entries whose value was 0. It is the shortest way to filter a map by value.values().removeIf(qty -> qty == 0) sees both key and value: entries starting withentrySet().removeIf and below 5 were removed, which tookp andpear .plum removes a batch of keys;keySet().removeAll(Set.of(...)) would keep only those keys.retainAll- An explicit iterator with
allows extra work per entry, such as logging what is dropped.it.remove()
The loop trap
Calling map.remove
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Map;
public class LoopTrap {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("apple", 5);
stock.put("pear", 0);
stock.put("plum", 3);
stock.put("fig", 0);
try {
for (String key : stock.keySet()) {
if (stock.get(key) == 0) {
stock.remove(key); // changes the map under the loop
}
}
} catch (ConcurrentModificationException e) {
System.out.println("map.remove inside for-each: ConcurrentModificationException");
}
}
}
Output:
map.remove inside for-each: ConcurrentModificationException
The for-each loop uses the key set's iterator. map.removeConcurrentModificationExceptionremoveIfremoveConcurrentHashMap
Removal through compute, ranges and eviction
Three other mechanisms remove entries as a side effect of something else: an update that reaches nothing, a range of sorted keys, and a cache that has grown too large.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class ComputeAndExpire {
public static void main(String[] args) {
Map<String, Integer> stock = new TreeMap<>(Map.of("apple", 5, "fig", 1, "kiwi", 8));
// compute / computeIfPresent / merge remove the entry when the function returns null
stock.computeIfPresent("fig", (k, qty) -> qty - 1 == 0 ? null : qty - 1);
System.out.println("sell last fig: " + stock);
stock.merge("kiwi", -8, (old, delta) -> old + delta == 0 ? null : old + delta);
System.out.println("merge to zero: " + stock);
// TreeMap ranges: remove a whole key range through a view
TreeMap<Integer, String> log = new TreeMap<>();
for (int t = 100; t <= 500; t += 100) {
log.put(t, "event@" + t);
}
log.headMap(300).clear(); // everything before t=300
System.out.println("after headMap(300).clear(): " + log.keySet());
System.out.println("pollFirstEntry: " + log.pollFirstEntry() + ", left " + log.keySet());
// A size-limited cache: LinkedHashMap removes the eldest entry automatically
Map<String, Integer> cache = new LinkedHashMap<>(16, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
return size() > 3;
}
};
for (String k : new String[] {"a", "b", "c"}) {
cache.put(k, k.length());
}
cache.get("a"); // access order: a is now newest
cache.put("d", 1); // evicts b, the least recently used
System.out.println("LRU cache: " + cache.keySet());
// clear, and removing with an empty result
stock.clear();
System.out.println("after clear: " + stock + " isEmpty=" + stock.isEmpty());
}
}
Output:
sell last fig: {apple=5, kiwi=8}
merge to zero: {apple=5}
after headMap(300).clear(): [300, 400, 500]
pollFirstEntry: 300=event@300, left [400, 500]
LRU cache: [c, a, d]
after clear: {} isEmpty=true
- When the function passed to
,computeIfPresent orcompute returnsmerge , the entry is removed. Selling the last fig and merging kiwi down to zero removed both, without a separatenull call.remove - On a
,TreeMap is a view of all keys below 300, and clearing it removed them from the map.headMap(300) removes and returns the smallest entry. This is a simple way to expire entries keyed by time; seepollFirstEntryNavigableMap . - A
in access order withLinkedHashMap returningremoveEldestEntry is an LRU cache: readingsize() > 3 made it recent, so addinga evictedd . More on thebTreeMap and LinkedHashMap page . removes everything.clear()
Maps that refuse removal, and keys that cannot be found
Removal can fail for reasons that have nothing to do with loops: the map may be read-only, its key type may not allow the lookup, or the key itself may have changed since it was inserted. The program tries each case and prints the result or the exception.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class CannotRemove {
interface Attempt {
Object run();
}
static void attempt(String label, Attempt a) {
try {
System.out.printf("%-38s -> %s%n", label, a.run());
} catch (RuntimeException e) {
System.out.printf("%-38s -> %s%n", label, e.getClass().getSimpleName());
}
}
public static void main(String[] args) {
// Maps that refuse removal
Map<String, Integer> fixed = Map.of("a", 1, "b", 2);
attempt("Map.of(...).remove(\"a\")", () -> fixed.remove("a"));
attempt("Map.of(...).remove(\"zzz\") (absent)", () -> fixed.remove("zzz"));
Map<String, Integer> backing = new HashMap<>(Map.of("a", 1, "b", 2));
Map<String, Integer> readOnly = Collections.unmodifiableMap(backing);
attempt("unmodifiableMap.remove(\"a\")", () -> readOnly.remove("a"));
attempt("unmodifiableMap.values().removeIf", () -> readOnly.values().removeIf(v -> v > 1));
backing.remove("a"); // the owner can still remove
attempt("view after the owner removed \"a\"", () -> readOnly);
// TreeMap compares keys, so a null key cannot even be looked up
TreeMap<String, Integer> sorted = new TreeMap<>(Map.of("a", 1));
attempt("TreeMap.remove(null)", () -> sorted.remove(null));
attempt("HashMap.remove(null) (no such key)", () -> new HashMap<>(backing).remove(null));
// A key that changes after insertion can no longer be found
Map<List<String>, String> byTags = new HashMap<>();
List<String> tags = new ArrayList<>(List.of("red"));
byTags.put(tags, "apple");
tags.add("sweet"); // hashCode changes
attempt("remove(mutated key)", () -> byTags.remove(tags));
attempt("remove(equal copy of the old key)", () -> byTags.remove(List.of("red")));
attempt("size afterwards", byTags::size);
attempt("entrySet().removeIf(all) still works", () -> byTags.entrySet()
.removeIf(e -> true) + ", size " + byTags.size());
}
}
Output:
Map.of(...).remove("a") -> UnsupportedOperationException
Map.of(...).remove("zzz") (absent) -> UnsupportedOperationException
unmodifiableMap.remove("a") -> UnsupportedOperationException
unmodifiableMap.values().removeIf -> UnsupportedOperationException
view after the owner removed "a" -> {b=2}
TreeMap.remove(null) -> NullPointerException
HashMap.remove(null) (no such key) -> null
remove(mutated key) -> null
remove(equal copy of the old key) -> null
size afterwards -> 1
entrySet().removeIf(all) still works -> true, size 0
- A map from
threwMap.of for every removal, even for a key that is not there. It does not check first; any attempt to change it fails. SeeUnsupportedOperationExceptionimmutable collections . refused removal through the map and through its views, but it is only a read-only window: when the owner removed "a" from the backing map, the view showedCollections.unmodifiableMap .{b=2} threwTreeMap.remove(null) , because it has to compare the key with the others. ANullPointerException allows oneHashMap key and simply returnednull .null- The list used as a key gained an element after insertion, so its
changed.hashCode then looked in the wrong bucket and found nothing, and an equal copy of the old key failed too, because the stored key no longer equals it. The entry stayed in the map, unreachable by key. Only a scan such asremove could still delete it. Use immutable keys: strings, numbers, records with immutable fields.entrySet().removeIf
A HashMap does not shrink after removal
A HashMap
import java.util.HashMap;
import java.util.Map;
public class NoShrink {
static long timeIteration(Map<Integer, Integer> map) {
long best = Long.MAX_VALUE;
long sum = 0;
for (int r = 0; r < 5; r++) {
long start = System.nanoTime();
for (int k = 0; k < 100; k++) { // 100 full iterations
for (Map.Entry<Integer, Integer> e : map.entrySet()) {
sum += e.getValue();
}
}
best = Math.min(best, System.nanoTime() - start);
}
if (sum == 42) {
System.out.println(); // keeps the loop alive
}
return best / 1000;
}
static long usedHeap() {
Runtime rt = Runtime.getRuntime();
for (int i = 0; i < 3; i++) {
System.gc();
}
return rt.totalMemory() - rt.freeMemory();
}
public static void main(String[] args) {
long base = usedHeap();
Map<Integer, Integer> big = new HashMap<>();
for (int i = 0; i < 1000000; i++) {
big.put(i, i);
}
long full = usedHeap() - base;
big.keySet().removeIf(k -> k >= 10); // keep only 10 entries
long afterRemove = usedHeap() - base;
Map<Integer, Integer> fresh = new HashMap<>(big); // a right-sized copy
Map<Integer, Integer> small = new HashMap<>();
for (int i = 0; i < 10; i++) {
small.put(i, i);
}
System.out.printf("1,000,000 entries: heap %6.1f MB%n", full / 1e6);
System.out.printf("after removing all but 10: heap %6.1f MB, size %d%n",
afterRemove / 1e6, big.size());
big = null;
System.out.printf("after replacing it by a copy: heap %6.1f MB%n",
(usedHeap() - base) / 1e6);
big = fresh;
System.out.println("100 iterations over 10 entries, best of 5:");
System.out.printf(" new HashMap<>(shrunk) copy: %,7d us%n", timeIteration(big));
Map<Integer, Integer> shrunkInPlace = new HashMap<>();
for (int i = 0; i < 1000000; i++) {
shrunkInPlace.put(i, i);
}
shrunkInPlace.keySet().removeIf(k -> k >= 10);
System.out.printf(" shrunk map itself, not copied: %,7d us%n",
timeIteration(shrunkInPlace));
System.out.printf(" map built with 10 entries: %,7d us%n", timeIteration(small));
}
}
Output (heap figures and rough timings from a 2-CPU Linux machine, JDK 21):
1,000,000 entries: heap 73.5 MB
after removing all but 10: heap 9.5 MB, size 10
after replacing it by a copy: heap 0.3 MB
100 iterations over 10 entries, best of 5:
new HashMap<>(shrunk) copy: 100 us
shrunk map itself, not copied: 206,450 us
map built with 10 entries: 50 us
- After the removal, the entries themselves were gone, but the heap still held several megabytes: the bucket table sized for a million entries, about two million slots of 4 bytes each.
- Iterating over the 10 remaining entries was thousands of times slower in the shrunk map than in a map built small, because an iterator walks every bucket of the table, empty or not.
- Copying the survivors with
created a right-sized table. Once the big map was dropped, its memory was released, and iterating the copy took only microseconds, in the same range as the map built small.new HashMap<>(shrunk)
So for a long-lived map that once held many entries and now holds few, such as a cache after a burst, replace it with a copy. clear()TreeMapLinkedHashMapLinkedHashMap
How fast is each approach?
The program removes the 100,000 entries with value 0 from a HashMap
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;
public class MapRemoveSpeed {
public static void main(String[] args) {
Map<Integer, Integer> base = new HashMap<>();
for (int i = 0; i < 1000000; i++) {
base.put(i, i % 10);
}
System.out.printf("remove entries with value 0 from a HashMap of %,d%n", base.size());
time("values().removeIf", base, m -> m.values().removeIf(v -> v == 0));
time("entrySet().removeIf", base, m -> m.entrySet().removeIf(e -> e.getValue() == 0));
time("iterator.remove", base, m -> {
for (Iterator<Integer> it = m.values().iterator(); it.hasNext(); ) {
if (it.next() == 0) {
it.remove();
}
}
});
time("collect keys, then remove", base, m -> {
List<Integer> keys = m.entrySet().stream().filter(e -> e.getValue() == 0)
.map(Map.Entry::getKey).toList();
keys.forEach(m::remove);
});
time("stream into a new map", base, m -> {
Map<Integer, Integer> kept = m.entrySet().stream().filter(e -> e.getValue() != 0)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
m.clear();
m.putAll(kept);
});
}
// Best of 3 runs, each on a fresh copy
static void time(String name, Map<Integer, Integer> base, Consumer<Map<Integer, Integer>> op) {
long best = Long.MAX_VALUE;
int size = 0;
for (int run = 0; run < 3; run++) {
Map<Integer, Integer> copy = new HashMap<>(base);
long t0 = System.nanoTime();
op.accept(copy);
best = Math.min(best, System.nanoTime() - t0);
size = copy.size();
}
System.out.printf(" %-28s %6.1f ms (%,d left)%n", name, best / 1e6, size);
}
}
Output (rough timings; 2-CPU Linux machine, JDK 21):
remove entries with value 0 from a HashMap of 1,000,000
values().removeIf 9.3 ms (900,000 left)
entrySet().removeIf 9.9 ms (900,000 left)
iterator.remove 5.4 ms (900,000 left)
collect keys, then remove 13.6 ms (900,000 left)
stream into a new map 96.9 ms (900,000 left)
- The view-based
calls and the explicit iterator were all fast and close to each other, because removing one entry from a hash map costs the same wherever it is. Unlike anremoveIf , a map has no shifting, so iterator removal is not a performance problem here.ArrayList - Collecting the keys first and removing them afterwards was a little slower, since it looks each key up a second time, but it is a reasonable pattern when the decision needs the whole map.
- Building a new map with a stream and copying it back was by far the slowest, because it creates 900,000 new entries. Filtering into a new map is fine when you want a new map anyway; to change a map in place, use
.removeIf
Which approach to use
| To remove | Use |
|---|---|
| One known key | map.remove(key) |
| A key only if it has a certain value | map.remove(key, value) |
| Entries by value | map.values().removeIf(v -> ...) |
| Entries by key and value | map.entrySet().removeIf(e -> ...) |
| A set of keys | map.keySet().removeAll(keys) |
| Inside a loop that does more work | An explicit iterator and it.remove() |
| A counter that reaches zero | mergecomputeIfPresentnull |
| Keys older than a cut-off | treeMap.headMap(cutoff).clear() |
| Oldest entries beyond a size limit | LinkedHashMap.removeEldestEntry |
Removing from lists is covered on