- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements