Search code examples
java-8functional-programmingjava-9option-type

How do I concisely write a || b where a and b are Optional values?


I'm happy with an answer in any language, but I ultimately want an answer in Java. (Java 8+ is fine. Not limited to Java 8. I've tried to fix the tags.)

If I have two Optional<Integer> values, how do I concisely compute the equivalent of a || b, meaning: a, if it's defined; otherwise b, if it's defined; otherwise empty()?

Optional<Integer> a = ...;
Optional<Integer> b = ...;
Optional<Integer> aOrB = a || b; // How to write this in Java 8+?

I know that I can write a.orElse(12), but what if the default "value" is also Optional?

Evidently, in C#, the operator ?? does what I want.


Solution

  • Optional<Integer> aOrB =  a.isPresent() ? a : b;