Optional.ifPresentOrElse()
Handle both present and empty cases of Optional in one call.
Porównanie kodu
✕ Java 8
Optional<User> user = findUser(id);
if (user.isPresent()) {
greet(user.get());
} else {
handleMissing();
}
✓ Java 9+
findUser(id).ifPresentOrElse(
this::greet,
this::handleMissing
);
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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.
Stare podejście
if/else on Optional
Nowoczesne podejście
ifPresentOrElse()
Od JDK
9
Poziom trudności
Początkujący
Wsparcie JDK
Optional.ifPresentOrElse()
Dostępne
Widely available since JDK 9 (Sept 2017)
Jak to działa
ifPresentOrElse() takes a Consumer for the present case and a Runnable for the empty case. It avoids the isPresent/get anti-pattern.
Powiązana dokumentacja