Java HashMap – Remove Entries

Learn about removing entries from a HashMap, including removing by key, with an iterator and bulk removal with a filter.

“To live is the rarest thing in the world. Most people exist, that is all.”
― Oscar Wilde

 

1. Introduction

After covering HashMap basics, iteration and searching/sorting, let us look at a few ways of removing entries from a HashMap.

2. Load CSV Data into HashMap

We use a HashMap into which CSV data has been loaded in the examples below. Check here for the code to do that.

3. Removing Single Item By Key

The HashMap API provides a method remove() which removes a single entry by key. Pretty straightforward.

namefreq.remove("Elicia");

// before:
Elisabeth : 203
Elisha : 50
Elicia : 7
Elias : 43

// after:
Elisabeth : 203
Elisha : 50
Elias : 43

An extension to remove() method provides the value along with the key and the mapping will be removed if the value matches what is currently stored.

4. Remove Many Entries with Iterator

You can remove entries during an iteration. First off, DO NOT do this. You will be rewarded with a ConcurrentModificationException in your face.

for (String name : subset.keySet()) {
    if ( name.endsWith("a") ) subset.remove(name);
}

Another way that DOES NOT work, because it attempts to modify the map in a loop.

subset
    .keySet()
    .stream()
    .filter(s -> s.endsWith("a"))
    .forEach(subset::remove);

Remove items in a loop using Iterator.remove() on the key set.

for (Iterator<String> it = subset.keySet().iterator() ; it.hasNext() ;){
    String name = it.next();
    if ( name.endsWith("a") ) it.remove();
}

Use a lambda predicate (on the key) to remove multiple entries in a single line of code.

subset.keySet().removeIf(s -> s.endsWith("a"));

To apply a removal condition on the value (or both key and value), use something like this:

subset.entrySet().removeIf(e -> e.getKey().equals("Elicia") || e.getValue().get(0) > 100);

// before
Ellen : 128
Elisabeth : 203
Elvis : 6
Eloise : 28
Eleanor : 33
Elicia : 7
Elaine : 182
Elisha : 50
Elias : 43
Eladio : 5
Elena : 19

// after:
Elvis : 6
Eloise : 28
Eleanor : 33
Elisha : 50
Elias : 43
Eladio : 5
Elena : 19

5. Bulk Removal of Entries

What if you want to remove entries whose keys you have in an array? Use removeAll() on the key set:

List<String> names = Arrays.asList("Eloise",
				   "Elisha",
				   "Ellen");
subset.keySet().removeAll(names);

Another way is to: a) search the map for matching keys b) collect the matching keys in a set c) remove these mappings.

List<String> matches = subset
    .keySet()
    .stream()
    .filter(s -> s.contains("n"))
    .collect(Collectors.toList());
subset.keySet().removeAll(matches);

// before:
Ellen : 128
Elisabeth : 203
Elvis : 6
Eloise : 28
Eleanor : 33
Elicia : 7
Elaine : 182
Elisha : 50
Elias : 43
Eladio : 5
Elena : 19

// after:
Elisabeth : 203
Elvis : 6
Eloise : 28
Elicia : 7
Elisha : 50
Elias : 43
Eladio : 5

To keep the mappings that match and remove everything else, use retainAll().

subset.keySet().retainAll(matches);

// after:
Ellen : 128
Eleanor : 33
Elaine : 182
Elena : 19

Summary

In this article, we learnt several ways of removing entries from a HashMap. Attempting to remove items while looping throws an exception unless the iterator is used for the removal. Using lambda is an easy way to remove mappings matching conditions on the key and/or value.