Class Optionals
Optional
.- Since:
- 1.14
-
Method Summary
Modifier and TypeMethodDescriptionstatic <T> Set
<T> static <A,
B> BiOptional <A, B> Ifa
andb
are present, returns aBiOptional
instance containing them; otherwise returns an emptyBiOptional
.ifPresent
(BiOptional<A, B> optional, CheckedBiConsumer<? super A, ? super B, E> consumer) Runsaction
if the pair is present.ifPresent
(Optional<A> left, Optional<B> right, CheckedBiConsumer<? super A, ? super B, E> consumer) Invokesconsumer
if bothleft
andright
are present.ifPresent
(Optional<T> optional, CheckedConsumer<? super T, E> consumer) Invokesconsumer
ifoptional
is present.ifPresent
(OptionalDouble optional, CheckedDoubleConsumer<E> consumer) Invokesconsumer
ifoptional
is present.ifPresent
(OptionalInt optional, CheckedIntConsumer<E> consumer) Invokesconsumer
ifoptional
is present.ifPresent
(OptionalLong optional, CheckedLongConsumer<E> consumer) Invokesconsumer
ifoptional
is present.static <A,
B> BiOptional <A, B> Similar toboth(java.util.Optional<? extends A>, java.util.Optional<? extends B>)
, but only evaluatesstep2
ifstep1
is present.static <A,
B> BiOptional <A, B> Similar toboth(java.util.Optional<? extends A>, java.util.Optional<? extends B>)
, but only evaluatesstep2
ifstep1
is present.static <T> Optional
<T> optional
(boolean condition, T value) Returns an Optional that wrapsvalue
ifcondition
is true andvalue
is not null, or elseempty()
.optionally
(boolean condition, CheckedSupplier<? extends T, E> supplier) Returns an Optional that wraps the nullable result fromsupplier
ifcondition
is true, or elseempty()
.
-
Method Details
-
optionally
public static <T,E extends Throwable> Optional<T> optionally(boolean condition, CheckedSupplier<? extends T, E> supplier) throws EReturns an Optional that wraps the nullable result fromsupplier
ifcondition
is true, or elseempty()
.Example:
Optional<Double> avg = optionally(count > 0, () -> sum / count);
- Throws:
NullPointerException
- ifsupplier
is nullE
- Since:
- 3.7
-
optional
Returns an Optional that wrapsvalue
ifcondition
is true andvalue
is not null, or elseempty()
.Example:
Optional<Foo> foo = optional(input.hasFoo(), input.getFoo());
- Since:
- 3.7
-
asSet
Returns an immutable singletonSet
whose only element is the contained instance if it is present; an empty immutableSet
otherwise.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 theresults
collection 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
-
both
Ifa
andb
are present, returns aBiOptional
instance containing them; otherwise returns an emptyBiOptional
.- Throws:
NullPointerException
- ifa
orb
is 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 evaluatesstep2
ifstep1
is present.Useful if
step2
is 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
- ifstep1
orstep2
is 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 evaluatesstep2
ifstep1
is present.Useful if
step2
is 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
- ifstep1
orstep2
is null- Since:
- 8.1
-
ifPresent
public static <E extends Throwable> Premise ifPresent(OptionalInt optional, CheckedIntConsumer<E> consumer) throws E Invokesconsumer
ifoptional
is present. Returns aPremise
object 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 regularif
statements.
- Throws:
E
-
ifPresent
public static <E extends Throwable> Premise ifPresent(OptionalLong optional, CheckedLongConsumer<E> consumer) throws E Invokesconsumer
ifoptional
is present. Returns aPremise
object 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 regularif
statements.
- Throws:
E
-
ifPresent
public static <E extends Throwable> Premise ifPresent(OptionalDouble optional, CheckedDoubleConsumer<E> consumer) throws E Invokesconsumer
ifoptional
is present. Returns aPremise
object 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 regularif
statements.
- Throws:
E
-
ifPresent
public static <T,E extends Throwable> Premise ifPresent(Optional<T> optional, CheckedConsumer<? super T, E> consumer) throws EInvokesconsumer
ifoptional
is present. Returns aPremise
object 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 regularif
statements.
- Throws:
E
-
ifPresent
public static <A,B, Premise ifPresentE extends Throwable> (Optional<A> left, Optional<B> right, CheckedBiConsumer<? super A, ? super B, throws EE> consumer) Invokesconsumer
if bothleft
andright
are present. Returns aPremise
object 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, Premise ifPresentE extends Throwable> (BiOptional<A, B> optional, CheckedBiConsumer<? super A, throws E? super B, E> consumer) Runsaction
if the pair is present. Allows chaining multipleBiOptional
andOptional
together. 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
-