Class Optionals


  • public final class Optionals
    extends java.lang.Object
    Utility methods for Optional, backporting Java 9+ operations to Java 8.

    This class emulates Optional.or() chaining from Java 9+, allowing lazy evaluation of alternative Optional values.

    Migration notice: Remove this class when upgrading to Java 11+. Replace Optionals.or() calls with native Optional.or() chaining.

    Since:
    3.28.0
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static <T> java.util.Optional<T> or​(java.util.function.Supplier<java.util.Optional<T>>... suppliers)
      Returns the first present Optional from the given suppliers.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Method Detail

      • or

        @SafeVarargs
        public static <T> java.util.Optional<T> or​(java.util.function.Supplier<java.util.Optional<T>>... suppliers)
        Returns the first present Optional from the given suppliers.

        Emulates Java 9+ Optional.or() chaining with varargs support:

        
         // Java 9+
         Optional<T> result = opt1.or(() -> opt2).or(() -> opt3);
        
         // Java 8 with Optionals
         Optional<T> result = Optionals.or(() -> opt1, () -> opt2, () -> opt3);
         

        Suppliers are evaluated lazily with short-circuit evaluation.

        Type Parameters:
        T - the type of the value
        Parameters:
        suppliers - suppliers of Optionals to evaluate in order
        Returns:
        the first present Optional, or empty if all are empty