Java HashMap remove() Method

Java HashMap Java HashMap

The remove() method is used to delete the key-value pair corresponding to the specified key key in the hashMap.

The syntax of the remove() method is:

hashmap.remove(Object key, Object value);

Note:hashmap is an object of the HashMap class.

Parameter Description:

  • key - the key
  • value (optional) - the value corresponding to key in the key-value pair

Return Value

If a key is specified, the value associated with the specified key is returned. If the specified key maps to null or the key does not exist in the HashMap, this method returns null.

If both key and value are specified, it returns true if the deletion succeeds, otherwise it returns false.

Example

The following example demonstrates the use of the remove() method:

Example

import java.util.HashMap;

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

        HashMap<Integer, String> sites = new HashMap<>();
        sites.put(1, "Google");
        sites.put(2, "Example");
        sites.put(3, "Taobao");
        System.out.println("HashMap: " + sites);

        // delete the mapping for key 2
        String siteName = sites.remove(2);  // return Example
        System.out.println("Return value: " + siteName);
        System.out.println("HashMap after deletion: " + sites);
    }
}

Executing the above program outputs the following result:

HashMap: {1=Google, 2=Example, 3=Taobao}
返回值: Example
删除后的 HashMap: {1=Google, 3=Taobao}

In the above example, we created a HashMap named sites. The code then uses the remove() method to delete the value corresponding to the specified key in sites, and the return value is that value.

The remove() method with two parameters key and value:

Example

import java.util.HashMap;

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

        HashMap<Integer, String> sites = new HashMap<>();
        sites.put(1, "Google");
        sites.put(2, "Example");
        sites.put(3, "Taobao");
        System.out.println("HashMap: " + sites);

        // delete the mapping for key 2
        Boolean flag1 = sites.remove(1, "Google");  // return true
        Boolean flag2 = sites.remove(2, "Weibo");  // return false
        System.out.println("Return value flag1: " + flag1);
        System.out.println("Return value flag2: " + flag2);
        System.out.println("HashMap after deletion: " + sites);
    }
}

Executing the above program outputs the following result:

返回值 flag1: true
返回值 flag2: false
删除后的 HashMap: {2=Example, 3=Taobao}

In the above example, we created a HashMap named sites, which contains 3 elements. Note these two lines:

Boolean flag1 = sites.remove(1, "Google");  // 存在的键值对返回 true
Boolean flag2 = sites.remove(2, "Weibo");   // 不存在的键值对返回 false

The remove() method includes key and value. If the key-value pair exists in the HashMap, it returns true; otherwise, it returns false.

Java HashMap Java HashMap

Other extensions