What is the HashMap clear() method in Java?

The clear function in Java for HashMaps clears and removes all of the keys and values, or mappings, from the specified HashMap. This function is accessed as java.util.HashMap.clear().

Syntax

Hash_Map.clear()

Parameters and return value

Parameters: This method does not take any parameters.

Return value: Calling this method clears the HashMap.

Code

Let’s have a look at a coding example of how to use this method to clear a hash mapping.

// import the util lib from Java
import java.util.*;
class HelloWorld {
public static void main( String args[] ) {
{
// Creating an empty HashMap based on our data
HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
// Introduce some data in the hashmap
hash_map.put(10, "Apple");
hash_map.put(20, "Banana");
hash_map.put(30, "Orange");
// Lets have a look at the HashMap
System.out.println("Hashmap: "+ hash_map);
// apply the clear method to the hashmap
hash_map.clear();
// Lets have a look a look at the hashmap
System.out.println("After applying clear method: " + hash_map);
}
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved