Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

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
Updated on: 2019-07-30T22:30:25+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements