Java Collection How to - Use null value as key in HashMap








Question

We would like to know how to use null value as key in HashMap.

Answer

import java.util.HashMap;
import java.util.Map;
//  ww  w  .j  a v  a2s  .c  om
public class Main {
  public static final void main(String[] args) {
    Map<String,String> map = new HashMap<>();
    map.put("one", "a");
    System.out.println("Size = " + map.size());
    map.put(null, "b");
    System.out.println("Size = " + map.size());
    System.out.println("map.get(null) = " + map.get(null));
  }
}

The code above generates the following result.