Streams Beginner

Handle both present and empty cases of Optional in one call.

โœ• Java 8
Optional<User> user = findUser(id);
if (user.isPresent()) {
    greet(user.get());
} else {
    handleMissing();
}
โœ“ Java 9+
findUser(id).ifPresentOrElse(
    this::greet,
    this::handleMissing
);
See a problem with this code? Let us know.
๐Ÿ“

Single expression

Both cases handled in one method call.

๐Ÿšซ

No get()

Eliminates the dangerous isPresent() + get() pattern.

๐Ÿ”—

Fluent

Chains naturally after findUser() or any Optional-returning method.

Old Approach
if/else on Optional
Modern Approach
ifPresentOrElse()
Since JDK
9
Difficulty
Beginner
Optional.ifPresentOrElse()
Available

Widely available since JDK 9 (Sept 2017)

ifPresentOrElse() takes a Consumer for the present case and a Runnable for the empty case. It avoids the isPresent/get anti-pattern.

Share ๐• ๐Ÿฆ‹ in โฌก