Benison Sam
Benison Sam

Reputation: 2825

Java: HashMap.getOrDefault returns null value

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

Upvotes: 9

Views: 10402

Answers (3)

ETO
ETO

Reputation: 7279

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.

Upvotes: 4

Seb34
Seb34

Reputation: 111

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.

Upvotes: 2

Tasos P.
Tasos P.

Reputation: 4114

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.

Upvotes: 10

Related Questions