Class Optionals


  • public final class Optionals
    extends Object
    Utility class for Optional.
    • Method Detail

      • ifPresentOrElse

        public static <T> void ifPresentOrElse​(Optional<T> optional,
                                               Consumer<? super T> action,
                                               Runnable emptyAction)
        In anticipation of Java 9 Optional#ifPresentOrElse.

        If a value is present in the given optional, performs the given action with the value, otherwise performs the given empty-based action.

        Parameters:
        optional - an Optional
        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 static <T> Stream<T> stream​(Optional<T> o)
        In anticipation of Java 9 Optional#stream.

        If a value is present, returns a sequential Stream containing only that value, otherwise returns an empty Stream.

        API Note: This method can be used to transform a Stream of optional elements to a Stream of present value elements:

          
         Stream<Optional<T>> os = .. 
         Stream<T> s = os.flatMap(Optional::stream)
         
        Returns:
        the optional value as a Stream