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/

Friday, 29 August 2025

Growing the Java Language #JVMLS

Just a blorb to remind me of the presentation by Brian Goetz during 2025 JVM Language Summit.

which was made available on the YouTube1.

P.S. in the link above was a reference to a presentation (in written form) by Guy Steel2, that was insightful.

References

[1] YouTube - Growing the Java Language #JVMLS
https://youtu.be/Gz7Or9C0TpM?si=ejyjWLRKwSY05AKW
[2] Growing a Language - Guy L. Steel Jr.
https://www.cs.virginia.edu/~evans/cs655/readings/steele.pdf