Java HashMap remove()

The syntax of the remove() method is:

hashmap.remove(Object key, Object value);

Here, hashmap is an object of the HashMap class.


remove() Parameters

The remove() method takes two parameters.

  • key - remove the mapping specified by this key
  • value (optional) - removes the mapping only if the specified key maps to the specified value

remove() Return Value

The remove() method removes the mapping and returns:

  • the previous value associated with the specified key
  • true if the mapping is removed

Note: The method returns null, if either the specified key is mapped to a null value or the key is not present on the hashmap.


Example 1: HashMap remove() With Key Parameter

Output

Languages: {1=Python, 2=C, 3=Java}
Updated Languages: {1=Python, 3=Java}

In the above example, we have created a hashmap named languages. Here, the remove() method does not have an optional value parameter. Hence, the mapping with key 2 is removed from the hashmap.


Example 2: HashMap remove() with Key and Value

Output

Countries: {Kathmandu=Nepal, Ottawa=Canada, Washington=America}
Countries after remove(): {Kathmandu=Nepal, Washington=America}

In the above example, we have created a hashmap named countries. Notice the line,

countries.remove("Ottawa", "Canada");

Here, the remove() method includes the optional value parameter (Canada). Hence, the mapping where the key Ottawa maps to value Canada is removed from the hashmap.

However, notice the line,

countries.remove("Washington", "USA");

Here, the hashmap does not contain any key Washington that is mapped with value USA. Hence, the mapping Washington=America is not removed from the hashmap.

Note: We can use the Java HashMap clear() method to remove all the mappings from the hashmap.