How to Remove all Mappings from HashMap in Java with Example

In the last tutorial we have seen how to remove a specific mapping from HashMap based on key. In this example we will be showing how to remove all the mappings from the HashMap. We will use clear() method for this.

Syntax :

public void clear() : According to Oracle docs, clear() method removes all of the mappings from the map.

Program to Remove all Mappings from HashMap

import java.util.*;

 public class HashMapRemoveExample {
    public static void main(String args[]) {
        
    // Creating a HashMap of int keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
 
    // Adding Key and Value pairs to HashMap
    hashmap.put(11,"Value1");
    hashmap.put(22,"Value2");
    hashmap.put(33,"Value3");
    hashmap.put(44,"Value4");
    hashmap.put(55,"Value5");
    hashmap.put(66,"Value6");
 
    // Showing HashMap Elements
    System.out.println("HashMap Elements: " + hashmap);

    // Removes all Mapping
    hashmap.clear();

    // Showing HashMap Elements after calling clear()
    System.out.println("After calling clear():");
    System.out.println("---------------------");
    System.out.println("HashMap Elements: " + hashmap); 
 
    }
}


Output

HashMap Elements: {33=Value3, 66=Value6, 22=Value2, 55=Value5, 11=Value1, 44=Value4}
After calling clear():
---------------------
HashMap Elements: {}



About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry