Monday, 6 October 2025

Optional.or

Was working on something, and I wanted to combine two optionals. In my case, I know that only one of the two will be present (or none), so combining them would be nice.

I'm not a big fan of using .ifPresent() and .get() combos. So, let's try streams.

Using streams, this looks something like:

Luckily we have a Optional.or() nowadays (Since Java 9), that I haven't used before.

It looks a lot better:

The awesome part (which is not shown in the example above) is that the or() accepts a Supplier, which means the Supplier will not be called if a value is present in the first Optional.

This is similar to the short-circuit evaluation1 present in the || operator of the common if-statement.

References

[1] Wikipedia - Short-circuit evaluation
https://en.wikipedia.org/wiki/Short-circuit_evaluation
[2] Baeldung - Guide To Java Optional
https://www.baeldung.com/java-optional
[3] Combine two Java Optionals
https://www.agalera.eu/combine-two-optionals/

No comments:

Post a Comment