Return from HashMap<String, String> when no key

Java

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

Careful - If you initialize it using

Map.of(key, val, key, val)

and then do a

get('key-that-isnt-there') 

then you'll get a null pointer exception.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDayanneView Question on Stackoverflow
Solution 1 - JavaBozhoView Answer on Stackoverflow
Solution 2 - JavalukastymoView Answer on Stackoverflow
Solution 3 - JavaForrestView Answer on Stackoverflow