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
?
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.
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.
It returns NULL when the map contains no such mapping for the key.
Why not simply:
return Optional.ofNullable(myMap.get(myKey));
JavaDocs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With