34

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
  • Optional#ofNullable, or better yet you can do some actions if the key is absent e.g. Map#computeIfAbsent
    – Rogue
    Nov 1, 2018 at 20:13
  • 2
    but think of that null a little, null might mean value not present or key actually mapped to null, depends of your map and application
    – Eugene
    Nov 1, 2018 at 20:14
  • @Eugene - Thanks. Yup, I am constructing the map myself from a stream so if the value doesn't exist then the entry would never have existed either. Still, I'm trying to cover all null cases. Nov 1, 2018 at 20:15

4 Answers 4

66

Why not simply:

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

JavaDocs

0
15

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));
-1

If the map contains a null value, the Optional.ofNullable(...) solution won't work. You need to do something like:

myMap.containsKey(myKey) ? Optional.of(myMap.get(myKey)) : Optional.empty();

It's annoying to have to check the map twice, but there doesn't seem to be a better way.

1
  • If the map contains a null value that you want to treat as non-empty Optional, then this pattern will not work anyway, as Optional.of(null) will throw an exception. You can use some kind of NULL object instead of null reference to put it into the Optional, but in this case it's better to put it into the Map in the first place, and then Optional.ofNullable(...) will work fine. Oct 31 at 13:48
-7

Functional and definitely too long solution:

myMap.entrySet().stream()
  .filter(it -> it.getKey().equals(myKey))
  .findFirst()
  .map(Map.Entry::getValue);
1
  • 10
    very bad idea as this does not leverage the map's index and do a full map scan
    – Cerber
    Nov 26, 2020 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.