How to make `Map::get` return either an `Optional` of the found value or `Optional.empty()`
Why not simply:
return Optional.ofNullable(myMap.get(myKey));
JavaDocs
This
Optional.of(myMap.getOrDefault(myKey, null));
or really
Optional.of(null);
would've failed with a NullPointerException
. As the javadoc states
Throws:
NullPointerException - ifvalue
is null
Optional#ofNullable
exists when you don't know if the value you're passing to it is null
or not:
Parameters:
value
- the possibly-null value to describe
And since Map#get(Object)
already returns null
when there is no entry for the given key
Returns:
the value to which the specified key is mapped, ornull
if this map contains no mapping for the key
you don't need to use getOrDefault
with a null
value for the default. You can instead directly use
Optional.ofNullable(myMap.get(myKey));