How to use null value as key in Java HashMap


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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements