Class Optionals
-
Method Summary
Modifier and TypeMethodDescriptionstatic <T> Set<T> static <A,B> BiOptional <A, B> Ifaandbare present, returns aBiOptionalinstance containing them; otherwise returns an emptyBiOptional.ifPresent(BiOptional<A, B> optional, CheckedBiConsumer<? super A, ? super B, E> consumer) Runsactionif the pair is present.ifPresent(Optional<A> left, Optional<B> right, CheckedBiConsumer<? super A, ? super B, E> consumer) Invokesconsumerif bothleftandrightare present.ifPresent(Optional<T> optional, CheckedConsumer<? super T, E> consumer) Invokesconsumerifoptionalis present.ifPresent(OptionalDouble optional, CheckedDoubleConsumer<E> consumer) Invokesconsumerifoptionalis present.ifPresent(OptionalInt optional, CheckedIntConsumer<E> consumer) Invokesconsumerifoptionalis present.ifPresent(OptionalLong optional, CheckedLongConsumer<E> consumer) Invokesconsumerifoptionalis present.static <A,B> BiOptional <A, B> Similar toboth(java.util.Optional<? extends A>, java.util.Optional<? extends B>), but only evaluatesstep2ifstep1is present.static <A,B> BiOptional <A, B> Similar toboth(java.util.Optional<? extends A>, java.util.Optional<? extends B>), but only evaluatesstep2ifstep1is present.static <C extends Collection<?>>
Optional<C> nonEmpty(C collection) static <T> Optional<T> optional(boolean condition, T value) Returns an Optional that wrapsvalueifconditionis true andvalueis not null, or elseempty().optionally(boolean condition, CheckedSupplier<? extends T, E> supplier) Returns an Optional that wraps the nullable result fromsupplierifconditionis true, or elseempty().
-
Method Details
-
optionally
public static <T, E extends Throwable> Optional<T> optionally(boolean condition, CheckedSupplier<? extends T, E> supplier) throws E Returns an Optional that wraps the nullable result fromsupplierifconditionis true, or elseempty().Example:
Optional<Double> avg = optionally(count > 0, () -> sum / count);- Throws:
NullPointerException- ifsupplieris nullE- Since:
- 3.7
-
optional
Returns an Optional that wrapsvalueifconditionis true andvalueis not null, or elseempty().Example:
Optional<Foo> foo = optional(input.hasFoo(), input.getFoo());- Since:
- 3.7
-
asSet
Returns an immutable singletonSetwhose only element is the contained instance if it is present; an empty immutableSetotherwise.This is useful when you are trying to apply some side-effects on the value contained in the
Optional:
While you could usefor (Foo foo : asSet(optionalFoo)) { // ... }optional.ifPresent(v -> ...), the lambda has limitations (no checked exceptions etc.). The body of the lambda can also become unwieldy if there are more than 5 lines of code, with conditionals and what not.If you need to add the Optional's contained value into another collection, consider
results.addAll(asSet(optional)). TheaddAll()side effect stands out more crisply than inoptional.ifPresent(results::add)where the important data flow into theresultscollection is somewhat buried and easy to miss.Lastly, if you need to check whether the optional contains a particular value, consider using
asSet(optional).contains(value).- Since:
- 6.1
-
nonEmpty
- Since:
- 8.3
-
both
Ifaandbare present, returns aBiOptionalinstance containing them; otherwise returns an emptyBiOptional.- Throws:
NullPointerException- ifaorbis null- Since:
- 5.7
-
inOrder
public static <A,B> BiOptional<A,B> inOrder(Optional<? extends A> step1, Supplier<? extends Optional<? extends B>> step2) Similar toboth(java.util.Optional<? extends A>, java.util.Optional<? extends B>), but only evaluatesstep2ifstep1is present.Useful if
step2is expensive or has side effects. For example, instead of:
Do:return parseUserId(userIdString) .flatMap(userId -> extractActiveWorklog() .flatMap(worklog -> processUserWorklog(userId, worklog)));return inOrder(parseUserId(userIdString), this::extractActiveWorklog) .flatMap((userId, worklog) -> processUserWorklog(userId, worklog));- Throws:
NullPointerException- ifstep1orstep2is null- Since:
- 8.1
-
inOrder
public static <A,B> BiOptional<A,B> inOrder(Optional<? extends A> step1, Function<? super A, ? extends Optional<? extends B>> step2) Similar toboth(java.util.Optional<? extends A>, java.util.Optional<? extends B>), but only evaluatesstep2ifstep1is present.Useful if
step2is expensive or has side effects. For example, instead of:
Do:return parseUserId(userIdString) .flatMap(userId -> extractActiveWorklog(userId) .flatMap(worklog -> processUserWorklog(userId, worklog)));return inOrder(parseUserId(userIdString), this::extractActiveWorklog) .flatMap((userId, worklog) -> processUserWorklog(userId, worklog));- Throws:
NullPointerException- ifstep1orstep2is null- Since:
- 8.1
-
ifPresent
public static <E extends Throwable> Premise ifPresent(OptionalInt optional, CheckedIntConsumer<E> consumer) throws E Invokesconsumerifoptionalis present. Returns aPremiseobject to alloworElse()and friends to be chained. For example:ifPresent(findId(), System.out::print) .or(() -> ifPresent(findName(), System.out::print)) .or(() -> ifPresent(findCreditCardNumber(), System.out::print)) .orElse(() -> System.out.print("no identity found"));This method is very similar to JDK
OptionalInt.ifPresent(java.util.function.IntConsumer)with a few differences:orElse()is chained fluently, compared toOptionalInt.ifPresentOrElse(java.util.function.IntConsumer, java.lang.Runnable).or()allows chaining arbitrary number of alternative options on arbitrary optional types.- Propagates checked exceptions from the
consumer. - Syntax is consistent across one-Optional and two-Optional
ifPresent()overloads. ifPresent(findId(), System.out::print)begins the statement with "if", which may read somewhat closer to regularifstatements.
- Throws:
E
-
ifPresent
public static <E extends Throwable> Premise ifPresent(OptionalLong optional, CheckedLongConsumer<E> consumer) throws E Invokesconsumerifoptionalis present. Returns aPremiseobject to alloworElse()and friends to be chained. For example:ifPresent(findId(), System.out::print) .or(() -> ifPresent(findName(), System.out::print)) .or(() -> ifPresent(findCreditCardNumber(), System.out::print)) .orElse(() -> System.out.print("id not found"));This method is very similar to JDK
OptionalLong.ifPresent(java.util.function.LongConsumer)with a few differences:orElse()is chained fluently, compared toOptionalLong.ifPresentOrElse(java.util.function.LongConsumer, java.lang.Runnable).or()allows chaining arbitrary number of alternative options on arbitrary optional types.- Propagates checked exceptions from the
consumer. - Syntax is consistent across one-Optional and two-Optional
ifPresent()overloads. ifPresent(findId(), System.out::print)begins the statement with "if", which may read somewhat closer to regularifstatements.
- Throws:
E
-
ifPresent
public static <E extends Throwable> Premise ifPresent(OptionalDouble optional, CheckedDoubleConsumer<E> consumer) throws E Invokesconsumerifoptionalis present. Returns aPremiseobject to alloworElse()and friends to be chained. For example:ifPresent(findMileage(), System.out::print) .or(() -> ifPresent(findName(), System.out::print)) .or(() -> ifPresent(findCreditCardNumber(), System.out::print)) .orElse(() -> System.out.print("id mileage found"));This method is very similar to JDK
OptionalDouble.ifPresent(java.util.function.DoubleConsumer)with a few differences:orElse()is chained fluently, compared toOptionalDouble.ifPresentOrElse(java.util.function.DoubleConsumer, java.lang.Runnable).or()allows chaining arbitrary number of alternative options on arbitrary optional types.- Propagates checked exceptions from the
consumer. - Syntax is consistent across one-Optional and two-Optional
ifPresent()overloads. ifPresent(findMileage(), System.out::print)begins the statement with "if", which may read somewhat closer to regularifstatements.
- Throws:
E
-
ifPresent
public static <T, E extends Throwable> Premise ifPresent(Optional<T> optional, CheckedConsumer<? super T, E> consumer) throws E Invokesconsumerifoptionalis present. Returns aPremiseobject to alloworElse()and friends to be chained. For example:ifPresent(findStory(), Story::tell) .or(() -> ifPresent(findGame(), Game::play)) .or(() -> ifPresent(findMovie(), Movie::watch)) .orElse(() -> print("Nothing to do"));This method is very similar to JDK
Optional.ifPresent(java.util.function.Consumer<? super T>)with a few differences:orElse()is chained fluently, compared toOptional.ifPresentOrElse(java.util.function.Consumer<? super T>, java.lang.Runnable).or()allows chaining arbitrary number of alternative options on arbitrary optional types.- Propagates checked exceptions from the
consumer. - Syntax is consistent across one-Optional and two-Optional
ifPresent()overloads. ifPresent(findStory(), Story::tell)begins the statement with "if", which may read somewhat closer to regularifstatements.
- Throws:
E
-
ifPresent
public static <A, B, E extends Throwable> Premise ifPresent(Optional<A> left, Optional<B> right, CheckedBiConsumer<? super A, ? super B, E> consumer) throws E Invokesconsumerif bothleftandrightare present. Returns aPremiseobject to alloworElse()and friends to be chained. For example:ifPresent(when, where, Story::tell) .orElse(() -> print("no story"));- Throws:
E
-
ifPresent
public static <A, B, E extends Throwable> Premise ifPresent(BiOptional<A, B> optional, CheckedBiConsumer<? super A, ? super B, E> consumer) throws ERunsactionif the pair is present. Allows chaining multipleBiOptionalandOptionaltogether. For example:ifPresent(both(firstName, lastName), (f, l) -> System.out.println(...)) .or(() -> ifPresent(firstName, f -> ...)) .or(() -> ifPresent(lastName, l -> ...)) .orElse(...);- Throws:
E- Since:
- 5.0
-