Java Collection How to - Remove key value pair from HashMap








Question

We would like to know how to remove key value pair from HashMap.

Answer

import java.util.HashMap;
/*from ww  w .  j a  v  a  2  s  . co  m*/
public class Main {
  public static void main(String[] args) {
    HashMap<String, Integer> map = new HashMap<String, Integer>();

    map.put("a", 1);
    map.put("b", 2);

    System.out.println("Before removal");
    for (String s : map.keySet()) {
      System.out.println(s);
    }

    System.out.println("\n\nAfter removal");

    map.remove("a");
    for (String s : map.keySet()) {
      System.out.println(s);
    }
  }
}

The code above generates the following result.