Easy Tutorial
❮ Java Properties Class String Search ❯

Java HashMap remove() Method

Java HashMap

The remove() method is used to delete the key-value pair associated with a specified key from the HashMap.

The syntax for the remove() method is:

hashmap.remove(Object key, Object value);

Note: hashmap is an object of the HashMap class.

Parameter Description:

Return Value

If only the key is specified, it returns the value associated with the specified key. 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 is successful, 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&lt;Integer, String> sites = new HashMap<>();
        sites.put(1, "Google");
        sites.put(2, "tutorialpro");
        sites.put(3, "Taobao");
        System.out.println("HashMap: " + sites);

        // Remove the mapping with key 2
        String siteName = sites.remove(2);  // returns tutorialpro
        System.out.println("Return value: " + siteName);
        System.out.println("HashMap after removal: " + sites);
    }
}

Executing the above program outputs:

HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Return value: tutorialpro
HashMap after removal: {1=Google, 3=Taobao}

In the above example, we created a HashMap named sites and used the remove() method to delete the value associated with a specified key, returning the value.

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

Example

import java.util.HashMap;

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

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

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

Executing the above program outputs:

Return value flag1: true
Return value flag2: false
HashMap after removal: {2=tutorialpro, 3=Taobao}

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

Boolean flag1 = sites.remove(1, "Google");  // existing key-value pair returns true

Boolean flag2 = sites.remove(2, "Weibo"); // Returns false for non-existent key-value pair

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

Java HashMap

❮ Java Properties Class String Search ❯