Easy Tutorial
❮ Dir Sub Java String Replaceall ❯

Java HashMap clear() Method

Java HashMap

The clear() method is used to remove all key/value pairs from the specified HashMap.

The syntax for the clear() method is:

hashmap.clear()

Note: hashmap is an object of the HashMap class.

Parameters:

Return Value

It does not return any value.

Example

The following example demonstrates the use of the clear() 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 all mappings from the HashMap
        sites.clear();
        System.out.println("After using clear() method: " + sites);
    }
}

Executing the above program outputs:

HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
After using clear() method: {}

In the above example, we created a HashMap named sites and used the clear() method to remove all key/value pairs from sites.

Note: We can also use the Java HashMap remove() method to remove the key-value pair corresponding to a key.

Reinitializing HashMap

In Java, we can also remove all key/value pairs by reinitializing the HashMap, for example:

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 all mappings from the HashMap
        // Reinitialize the hashmap
        sites = new HashMap<>();
        System.out.println("New HashMap: " + sites);
    }
}

Executing the above program outputs:

HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
New HashMap: {}

In the above example, we created a HashMap named sites that contains 3 elements. Note this line:

sites = new HashMap<>();

The above code does not remove all items from the HashMap; instead, it creates a new HashMap and assigns it to sites, and the original key-value pairs of sites will be garbage collected.

Java HashMap

❮ Dir Sub Java String Replaceall ❯