Class Optionals

java.lang.Object
org.kiwiproject.base.Optionals

public final class Optionals extends Object
Utility methods for instances of Optional, and which are not already present in Optional.
  • Method Details

    • ifPresentOrElseThrow

      public static <T> void ifPresentOrElseThrow(Optional<T> optional, Consumer<? super T> action, Supplier<? extends RuntimeException> exceptionSupplier)
      Takes an action if the optional is present, otherwise throws a RuntimeException that is created by the given Supplier.

      Note that only RuntimeExceptions can be thrown. Use ifPresentOrElseThrowChecked(Optional, Consumer, Supplier) if you need to throw a checked exception.

      Type Parameters:
      T - the type parameter
      Parameters:
      optional - the Optional to act upon
      action - action to be performed if a value is present in optional
      exceptionSupplier - supplier for a RuntimeException that will be thrown if optional is empty
    • ifPresentOrElseThrowChecked

      public static <T, E extends Exception> void ifPresentOrElseThrowChecked(Optional<T> optional, Consumer<? super T> action, Supplier<E> checkedExceptionSupplier) throws E
      Takes an action if the optional is present, otherwise throws a checked exception that is created by the given Supplier.
      Type Parameters:
      T - the type parameter
      E - the type of checked exception
      Parameters:
      optional - the Optional to act upon
      action - action to be performed if a value is present in optional
      checkedExceptionSupplier - supplier for the checked exception that will be thrown if optional is empty
      Throws:
      E - if the optional is empty