Java Collection How to - Remove (all) values from HashMap








Question

We would like to know how to remove (all) values from HashMap.

Answer

// w w w.j  a va  2s.co  m
import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap<String,String> hMap = new HashMap<String,String>();

    hMap.put("1", "One");
    hMap.put("2", "Two");
    hMap.put("3", "Three");

    Object obj = hMap.remove("2");
    System.out.println(obj + " Removed from HashMap");
  }
}

The code above generates the following result.

Remove all values from HashMap

/*w  w w . jav  a 2s .c  o  m*/
import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap<String,String> hMap = new HashMap<String,String>();

    hMap.put("1", "One");
    hMap.put("2", "Two");
    hMap.put("3", "Three");

    hMap.clear();
    System.out.println(hMap.size());
  }
}

The code above generates the following result.