3

I have three java8 Optionals, and want to return whichever one is actually present in a preferred order. It seems like there should be an easy way to chain them like so:

return optionalA.orElseIfPresent(optionalB).orElseIfPresent(optionalC);

if all three are empty, then an Optional.empty() ought to be returned.

the existing orElse and orElseGet are not really up to the task - they must return an actual value, so it's not possible for the remaining fallbacks to be Optionals themselves.

In the worst case I can have a long list of ifPresent() checks, but there just seems like there's a better way to go about it?

Nathan
  • 1,396
  • 3
  • 18
  • 32

2 Answers2

7
return Stream.of(optional1, optional2, optional3)
             .filter(Optional::isPresent)
             .map(Optional::get)
             .findFirst();
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
4

I like JB Nizet's answer (upvoted as well). Alternatively, using only Optional (for whatever reason):

Optional.ofNullable(
    optionalA.orElse(
        optionalB.orElse(
            optionalC.orElse(null))
        )
    );

which falls into indentation/parenthesis madness and I personally do not like.

ThanksForAllTheFish
  • 7,101
  • 5
  • 35
  • 54
  • 1
    The stream answer might be "prettier", but this solution is simpler and more transparent (and, incidentally, more efficient.) – Brian Goetz Apr 09 '16 at 14:51