What does a HashMap<String,String>
return when I call map.get("key") and I don't have an entry with the key "key" in the HashMap?
The Java HashMap getOrDefault() method returns the specified default value if the mapping for the specified key is not found in the hashmap. Otherwise, the method returns the value corresponding to the specified key.
If the key is not present in the map, get() returns null. The get() method returns the value almost instantly, even if the map contains 100 million key/value pairs.
HashMap and LinkedHashMap allows null keys and null values but TreeMap doesn't allow any null key or value. Map can't be traversed so you need to convert it into Set using keySet() or entrySet() method.
Return Value: The method returns boolean true if the map is empty or does not contain any mapping pairs else boolean false.
It returns null
. It's written in the documentation.
Returns: the value to which the specified key is mapped, or null if this map contains no mapping for the key
The first thing to do when you have such a specific question is to consult the documentation. Java APIs are documented reasonably well and tell you what is returned, what exceptions are thrown and what each argument means.
You can:
Check in your IDE
Map<String, String> map = new HashMap<String, String>(); map.put("foo", "fooValue"); System.out.println(map.get("bar")); // null
Check documentation - HashMap get() method description:
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With