Home

orElseorElseGetorElseThrow

orElseorElseGetorElseThrow is a shorthand reference to the trio of methods in Java's Optional type that handle empty values: orElse, orElseGet, and orElseThrow. They provide different strategies for obtaining a value when the Optional is empty and are commonly used to express fallback behavior in a fluent style.

orElse(T other) returns the contained value if present; otherwise it returns the provided other value. The other

orElseGet(Supplier<? extends T> supplier) returns the contained value if present; otherwise it calls supplier.get() to obtain

orElseThrow() returns the contained value if present; otherwise it throws NoSuchElementException. There is also orElseThrow(Supplier<? extends

Usage considerations include choosing between eager and lazy fallbacks (orElse vs orElseGet) and deciding whether a

Examples:

Optional<String> opt = Optional.ofNullable(getName());

String a = opt.orElse("default");

String b = opt.orElseGet(() -> computeDefaultName());

String c = opt.orElseThrow(() -> new IllegalStateException("Name missing"));

is
evaluated
eagerly
at
the
time
of
the
call,
so
any
computation
used
to
create
other
will
occur
regardless
of
whether
a
value
exists.
a
fallback
value.
The
supplier
is
evaluated
lazily,
meaning
it
runs
only
when
the
Optional
is
empty,
which
can
save
work
for
expensive
computations.
X>
exceptionSupplier)
to
throw
a
custom
exception
supplied
by
the
caller.
missing
value
should
be
treated
as
an
error
(orElseThrow)
or
as
a
normal
default.
These
methods
help
avoid
null
checks
by
providing
explicit
handling
paths
for
present
and
absent
values.