How to use null value as key in Java HashMap

Java 8Object Oriented ProgrammingProgramming

Yes, you can set null as key in Java HashMap. For this, let’s first create a HashMap with key and value pair −

Map<String,String>map = new HashMap<>();
map.put("Football", "A");
map.put("Squash", "B");
map.put("Cricket", "C");
map.put("Hockey", "D");
map.put("Rugby", "E");

Now, let’s add null value as key −

map.put(null, "H");

You can try to get the value for key as “null” −

map.get(null);

Example

 Live Demo

import java.util.HashMap;
import java.util.Map;
public class Demo {
   public static final void main(String[] args) {
      Map<String,String>map = new HashMap<>();
      map.put("Football", "A");
      map.put("Squash", "B");
      map.put("Cricket", "C");
      map.put("Hockey", "D");
      map.put("Rugby", "E");
      map.put("Golf", "F");
      map.put("Archery", "G");
      System.out.println("Size of HashMap = " + map.size());
      map.put(null, "H");
      System.out.println("Updated Size of HashMap = " + map.size());
      System.out.println("For null = " + map.get(null));
   }
}

Output

Size of HashMap = 7
Updated Size of HashMap = 8
For null = H
raja
Published on 25-Apr-2019 09:30:00
Advertisements