I was fetching key from a constant map earlier using HashMap.
On passing a NULL key at containsKey()
, I used to get FALSE.
To make the code look fancy, I tried java-8 over it. So, instead of HashMap, I started using Map.ofEntries to build my map
Surprisingly, I got Null Pointer Exception when a Null key was passed to containsKey()
method
String str = null;
Map<String,String> hashMap = new HashMap<>();
hashMap.put("k1", "v1");
System.out.print(hashMap.containsKey(str)); // This gives false
Map<String,String> ofEntriesMap = Map.ofEntries( Map.entry("k1", "v1"));
System.out.print(ofEntriesMap.containsKey(str)); // Why this gives Null Pointer Exception ?
I am unable to figure out, why it is behaving differently at Map.ofEntries
.
What is the best way to handle this situation ?