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

A map has no positions, so entries are removed by key, either directly with remove(key) or through one of its three views. keySet(), values() and entrySet() are live views backed by the map: removing an element from a view removes the whole entry from the map. The views support remove, removeIf, removeAll, retainAll and iterator removal, but not adding.

In a HashMap, removing an entry finds its bucket by hash, unlinks it, and never shrinks the table. In a TreeMap it rebalances the tree. Both make removal while a for-each loop is running a modification that the loop's iterator detects, which is the most common map removal bug.

Ways to remove from a map
CodeSinceRemovesBest for
map.remove(key)Java 1.2One entry; returns its old valueA known key
map.remove(key, value)Java 8The entry only if it has that valueConditional removal, concurrent maps
values().removeIf(...)Java 8Entries whose value matchesConditions on values
entrySet().removeIf(...)Java 8Entries matching a key-and-value conditionConditions on both
keySet().removeAll(keys)Java 1.2All listed keysA batch of keys
Iterator.remove()Java 1.2The current entryLoops with extra work per entry
compute, computeIfPresent, merge returning nullJava 8The entry being updatedCounters that reach zero
headMap, tailMap, subMap + clear()Java 1.2A key range of a sorted mapExpiring old keys
removeEldestEntryJava 1.4The oldest entry, automaticallySize-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 null value, because that is the case where the return value of remove becomes ambiguous.

Java
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:

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
  • remove(key) returns the value the key had, 0 for pear, or null if the key was absent.
  • remove(key, value) removes only when the key currently maps to that value: apple with 9 stayed, with 5 it was removed. On a ConcurrentHashMap this check and removal happen atomically.
  • When a map can hold null values, remove returns null both for a key mapped to null and for a missing key, as x and y show. Check containsKey first if the difference matters.

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.

Java
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:

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}
  • values().removeIf(qty -> qty == 0) removed both entries whose value was 0. It is the shortest way to filter a map by value.
  • entrySet().removeIf sees both key and value: entries starting with p and below 5 were removed, which took pear and plum.
  • keySet().removeAll(Set.of(...)) removes a batch of keys; retainAll would keep only those keys.
  • An explicit iterator with it.remove() allows extra work per entry, such as logging what is dropped.

The loop trap

Calling map.remove inside a for-each loop over the same map looks natural, and the program shows what it does.

Java
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:

Output
map.remove inside for-each: ConcurrentModificationException

The for-each loop uses the key set's iterator. map.remove changes the map behind the iterator's back, and the iterator's next call notices the changed modification count and throws ConcurrentModificationException. Depending on where the removed key sits, the loop may also end without an exception and skip entries, which is worse. Use removeIf on a view or the iterator's own remove. A ConcurrentHashMap tolerates removal during iteration, as the ConcurrentHashMap page shows.

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.

Java
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:

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, compute or merge returns null, the entry is removed. Selling the last fig and merging kiwi down to zero removed both, without a separate remove call.
  • On a TreeMap, headMap(300) is a view of all keys below 300, and clearing it removed them from the map. pollFirstEntry removes and returns the smallest entry. This is a simple way to expire entries keyed by time; see NavigableMap.
  • A LinkedHashMap in access order with removeEldestEntry returning size() > 3 is an LRU cache: reading a made it recent, so adding d evicted b. More on the TreeMap and LinkedHashMap page.
  • clear() removes everything.

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.

Java
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:

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 Map.of threw UnsupportedOperationException for every removal, even for a key that is not there. It does not check first; any attempt to change it fails. See immutable collections.
  • Collections.unmodifiableMap 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 showed {b=2}.
  • TreeMap.remove(null) threw NullPointerException, because it has to compare the key with the others. A HashMap allows one null key and simply returned null.
  • The list used as a key gained an element after insertion, so its hashCode changed. remove 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 as entrySet().removeIf could still delete it. Use immutable keys: strings, numbers, records with immutable fields.

A HashMap does not shrink after removal

A HashMap grows its bucket table as entries are added, but never makes it smaller when they are removed. The program fills a map with a million entries, removes all but 10, and measures the heap and the cost of iterating, compared with a fresh copy and a map that only ever held 10 entries.

Java
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):

Output
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 new HashMap<>(shrunk) 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.

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() has the same limitation: it empties the table but keeps its size. TreeMap and LinkedHashMap iteration follows the entries, not a table, so they do not have the slow-iteration problem, although LinkedHashMap keeps its table too.

How fast is each approach?

The program removes the 100,000 entries with value 0 from a HashMap of a million, five ways, each on a fresh copy and keeping the fastest of three runs.

Java
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):

Output
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 removeIf 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 an ArrayList, a map has no shifting, so iterator removal is not a performance problem here.
  • 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

Choosing a map removal method
To removeUse
One known keymap.remove(key)
A key only if it has a certain valuemap.remove(key, value)
Entries by valuemap.values().removeIf(v -> ...)
Entries by key and valuemap.entrySet().removeIf(e -> ...)
A set of keysmap.keySet().removeAll(keys)
Inside a loop that does more workAn explicit iterator and it.remove()
A counter that reaches zeromerge or computeIfPresent returning null
Keys older than a cut-offtreeMap.headMap(cutoff).clear()
Oldest entries beyond a size limitLinkedHashMap.removeEldestEntry

Removing from lists is covered on removing elements from a list, and looping over maps on looping through a map.