Java: HashMap.getOrDefault returns null value

Viewed 3078

I'm fairly new to Java coming from a Python and C# background. I don't know why I am getting a null value for HashMap.getOrDefault() when from my understanding, this method is built in the first place to avoid NullPointer exceptions. The people object is not null, neither is idKey.

Screen Shot

3 Answers

The getOrDefault() will return the default value when the key is not found, as per the documentation. If the key is found but the value is null, then null will be returned.

So, it seems that your map actually contains the key but the corresponding value is null.

As @TasosP already mentioned, your map most likely contains a null value. You could deal with it as follows:

int itemId = Optional.ofNullable(people.get(idKey))
                     .map(Object::toString)
                     .map(Integer::parseInt)
                     .orElse(0);

The code snippet above will handle both missing and null values.

HashMap.getOrDefault() returns the value to which the key is mapped and default value if there is no mapping. In your case, the only explanation is that idKey is present in people and mapped to null.

The following code returns null:

java.util.Map<String, String> map = new java.util.HashMap<>();
map.put("foo", null);
return map.getOrDefault("foo", "bar");

You get bar if you remove the put call.

Related