Class OptionalUtils


  • public final class OptionalUtils
    extends java.lang.Object
    Functions that make working with optionals easier.
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static <T> void ifPresentOrElse​(java.util.Optional<T> value, java.util.function.Consumer<T> action, java.lang.Runnable emptyAction)
      Invokes a consumer if the Optional has a value, otherwise invoked a Runnable when the Optional is empty.
      static <T> java.util.Optional<T> or​(java.util.Optional<T> value, java.util.function.Supplier<java.util.Optional<? extends T>> supplier)
      Retrieves the value of the optional if present or invokes the supplier for a value.
      static <T> java.util.stream.Stream<T> stream​(java.util.Optional<T> value)
      Converts an Optional into a Stream that can be used in a flatmap.
      • Methods inherited from class java.lang.Object

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

      • or

        public static <T> java.util.Optional<T> or​(java.util.Optional<T> value,
                                                   java.util.function.Supplier<java.util.Optional<? extends T>> supplier)
        Retrieves the value of the optional if present or invokes the supplier for a value.
        Type Parameters:
        T - Type of value.
        Parameters:
        value - Value to check.
        supplier - Supplier for a value if no value is present.
        Returns:
        A value of type T.
      • stream

        public static <T> java.util.stream.Stream<T> stream​(java.util.Optional<T> value)
        Converts an Optional into a Stream that can be used in a flatmap.

        This is a polyfill of Java 9's Optional#stream.

        Type Parameters:
        T - Value type.
        Parameters:
        value - Value to convert to a stream.
        Returns:
        A stream that contains a present value or a stream that is empty.
      • ifPresentOrElse

        public static <T> void ifPresentOrElse​(java.util.Optional<T> value,
                                               java.util.function.Consumer<T> action,
                                               java.lang.Runnable emptyAction)
        Invokes a consumer if the Optional has a value, otherwise invoked a Runnable when the Optional is empty.
        Type Parameters:
        T - Type of value.
        Parameters:
        value - Value to check.
        action - Action to invoke if a value is present.
        emptyAction - Runnable to invoke if a value is not present.