How to make `Map::get` return either an `Optional` of the found value or `Optional.empty()`

Viewed 22811

I'm trying to do this:

return Optional.of(myMap.getOrDefault(myKey, null));

Really, what I want is to return an Optional.of(foundVal) if found, otherwise Optional.empty(). I don't believe Optional.of(null) equates to that. What syntax does what I want to do?

That is, how can I get a map get to return a proper Optional?

3 Answers

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 - if value 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, or null 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));

Functional and definitely too long solution:

myMap.entrySet().stream()
  .filter(it -> it.getKey().equals(myKey))
  .findFirst()
  .map(Map.Entry::getValue);
Related