Remove all values from HashMap in Java


To remove all values from HashMap, use the clear() method.

First, let us create a HashMap.

HashMap hm = new HashMap();

Add some elements to the HashMap

hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
hm.put("Backpack", new Integer(1200));

Now, remove all the elements

hm.clear();

The following is an example to remove all values from HashMap.

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create hash map
      HashMap hm = new HashMap();
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      hm.put("Backpack", new Integer(1200));
      System.out.println("Map = "+hm);
      hm.clear();
      System.out.println("Map after removing all the elements (blank)= "+hm);
   }
}

The following is the output

Map = {Backpack=1200, Belt=600, Wallet=700}
Map after removing all the elements (blank)= {}

Updated on: 30-Jul-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements