Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 393
slackwing Avatar asked Nov 01 '18 20:11

slackwing


People also ask

What does map get return if not found?

Map get() method If the key is not present in the map, get() returns null. The get() method returns the value almost instantly, even if the map contains 100 million key/value pairs.

How do you return Optional value?

The get() method of Optional is simply used to return a value from the Optional object. Suppose the value is not present, then it throws the exception NoSuchElementException.

Does map get return null?

It returns NULL when the map contains no such mapping for the key.


1 Answers

Why not simply:

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

JavaDocs

like image 68
Eugene Avatar answered Oct 12 '22 09:10

Eugene