This post will discuss how to remove a key from a Map in Java.

1. Using remove() method

The standard solution is to remove the mapping for a key from a Map in Java is using the remove() method of the Map interface. When the remove() method is called upon a key key, a mapping from key k to value v is removed for which Objects.equals(key, k) holds. This equality holds true for other examples in this post.

Download  Run Code

Output:

{Java=1995, Ruby=1995}

 
You can also call the remove() method on the set view of keys returned by the keySet() method. This works since the returned set is backed by the map, and any changes made to the set are reflected in the map as well. This holds true for the entrySet() method as well.

Download  Run Code

Output:

{Java=1995, Ruby=1995}

2. Using removeIf() method

Since Java 8, you can use the removeIf() method to remove all entries from the map that satisfy the given predicate. The following code demonstrates its usage:

Download  Run Code

Output:

{Java=1995, Ruby=1995}

 
Here’s an equivalent example using the keySet() method:

Download  Run Code

Output:

{Java=1995, Ruby=1995}

3. Using removeAll() method

A plausible way in Java 8 and above is using the removeAll() method, which removes all mappings associated with the specified keys.

Download  Run Code

Output:

{Ruby=1995}

That’s all about removing a key from a Map in Java.