How to delete all elements from HashMap

We can delete all element from hashmap using clear() method . We have given one example here . Firstly we have created one hashmap then add element in it . After that we have used clear method for delete all element from hashmap.

import java.util.HashMap;
import java.util.Map;

public class HashMapDeleteAll {

public static void main(String[] args) {

Map<Integer,String> hm = new HashMap<Integer,String>();

* Associates the specified value with the specified key in
this map (optional operation). If the map previously
contained a mapping for the key, the old value is
replaced by the specified value
hm.put(2, "amit");
hm.put(5, "yogesh");

//print hashmap
System.out.println("Before Clear HashMap is = "+hm);

* The map will be empty after this call returns.


System.out.println("After Clear HashMap is ="+hm);





Before Clear HashMap is = {1=ankush, 2=amit, 3=shivam, 4=ankit, 5=yogesh}

After Clear HashMap is ={}


Leave a Reply

Your email address will not be published. Required fields are marked *

7 + 2 =