Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return from HashMap<String, String> when no key

Tags:

java

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?

like image 876
Dayanne Avatar asked Mar 07 '11 14:03

Dayanne


People also ask

What does HashMap return if key not found?

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.

What if key is not present in HashMap?

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.

Can HashMap have empty key?

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.

What does an empty HashMap return?

Return Value: The method returns boolean true if the map is empty or does not contain any mapping pairs else boolean false.


2 Answers

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.

like image 113
Bozho Avatar answered Sep 22 '22 01:09

Bozho


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.

like image 33
lukastymo Avatar answered Sep 24 '22 01:09

lukastymo