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

import java.util.HashMap;

class Main {
  public static void main(String[] args){

    // create a HashMap
    HashMap<Integer, String> languages = new HashMap<>();

    // add mappings to HashMap
    languages.put(1, "Python");
    languages.put(2, "C");
    languages.put(3, "Java");
    System.out.println("Languages: " + languages);

    // remove the mapping with key 2
    languages.remove(2);  // return C

    System.out.println("Updated Languages: " + languages);


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

import java.util.HashMap;

class Main {
  public static void main(String[] args) {
    // create an HashMap
    HashMap<String, String> countries = new HashMap<>();

    // insert items to the HashMap
    countries.put("Washington", "America");
    countries.put("Ottawa", "Canada");
    countries.put("Kathmandu", "Nepal");
    System.out.println("Countries: " + countries);

    // remove mapping {Ottawa=Canada}
    countries.remove("Ottawa", "Canada");  // return true

    // remove mapping {Washington=USA}
    countries.remove("Washington", "USA");  // return false

    System.out.println("Countries after remove(): " + countries);


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.

Also Read:

Did you find this article helpful?