Search code examples
javajava-8option-type

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


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?


Solution

  • Why not simply:

    return Optional.ofNullable(myMap.get(myKey));
    

    JavaDocs