Java Utility Library

Java HashMap - clear() Method



The java.util.HashMap.clear() method is used to clear all key-value mappings of the map. This method makes the map empty with a size of zero.

Syntax

public void clear()

Parameters

No parameter is required.

Return Value

void type.

Exception

NA

Example:

In the example below, the java.util.HashMap.clear() method is used to clear all key-value mappings of the given map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a hash map
    HashMap<Integer, String> MyMap = new HashMap<Integer, String>();

    //populating the map
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");
    MyMap.put(104, "Jo");

    //printing the map
    System.out.println("Before applying clear() method.");
    System.out.println("MyMap contains: " + MyMap);

    //clearing all mapping
    MyMap.clear();

    //printing the map again
    System.out.println("\nAfter applying clear() method."); 
    System.out.println("MyMap contains: " + MyMap);   
  }
}

The output of the above code will be:

Before applying clear() method.
MyMap contains: {101=John, 102=Marry, 103=Kim, 104=Jo}

After applying clear() method.
MyMap contains: {}

❮ Java.util - HashMap