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

  • A+

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?


Why not simply:

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



:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: