Class OptionalHelper<T>

  • Type Parameters:
    T - the type of the underlying optional value

    public class OptionalHelper<T>
    extends Object
    A wrapper on top of Optional to replicate some of the new Java9 methods.
    • Method Detail

      • from

        public static <T> OptionalHelper<T> from​(Optional<T> optional)
        Static factory method to create a new OptionalHelper instance.
        Type Parameters:
        T - the type of the underly optional value
        Parameters:
        optional - the optional to wrap
        Returns:
        the created OptionalHelper instance
      • asOptional

        public Optional<T> asOptional()
        Get the underlying Optional instance.
        Returns:
        the wrapped Optional
      • or

        public OptionalHelper<T> or​(Supplier<? extends Optional<T>> supplier)
        If the underlying Optional does not have a value, set it to the Optional produced by the supplying function.
        Parameters:
        supplier - the supplying function that produces an Optional
        Returns:
        returns this instance of OptionalHelper with the same the underlying Optional if a value is present, otherwise with the Optional produced by the supplying function.
        Throws:
        NullPointerException - if the supplying function is null or produces a null result
      • ifPresentOrElse

        public void ifPresentOrElse​(Consumer<T> action,
                                    Runnable emptyAction)
        If a value is present, performs the given action with the value, otherwise performs the given empty-based action.
        Parameters:
        action - the action to be performed, if a value is present
        emptyAction - the empty-based action to be performed, if no value is present
        Throws:
        NullPointerException - if a value is present and the given action is null, or no value is present and the given empty-based action is null.
      • stream

        public Stream<T> stream()
        If a value is present, returns a sequential Stream containing only that value, otherwise returns an empty Stream.
        Returns:
        the optional value as a Stream