Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java Util Map remove(key, value)

Java.Util.Map.remove(key, value)

The method Map.remove(Object key, Object value) removes entry for the key when its current mapping is equal to the given value.

Method signature

The signature of the Map.remove(Object key, Object value) method is as follows:

default boolean remove(Object key, Object value)

The method is available since Java 8.


  • Object key: key with which the value is associated,
  • Object value: expected value associated with the key.

Return value

True when the value was removed.


  • NullPointerException: when the given key or value is null and the map doesn’t allow null keys or values (optional)
  • UnsupportedOperationException: if the put operation is not supported by this map (optional)
  • ClassCastException: if the key or value is of not acceptable by this map (optional)

Example usage

In the following code we use java.util.Map.remove(Object key, Object value):


import java.util.HashMap;
import java.util.Map;

public class MapExamples {

    public static void main(String[] args) {
        Map<Integer,String> nameForId = new HashMap<>();
        nameForId.put(1, "Java");
        System.out.println("Original map: " + nameForId);

        nameForId.remove(1, "Clojure");
        System.out.println("Not removed: " + nameForId);

        nameForId.remove(1, "Java");
        System.out.println("Removed: " + nameForId);

The above code produces the following output:

Original map: {1=Java}
Not removed: {1=Java}
Removed: {}


Share with the World!