Optional ifPresentOrElse Branch
Handle both branches of an Optional in one call with ifPresentOrElse: the value action and the empty action live side by side, no if-get wrapping.
Code
import java.util.Optional;
public class SessionRouter {
static Optional<String> currentSession() {
// 演示:切换返回值观察两条分支
return Optional.empty();
}
public static void main(String[] args) {
// ifPresentOrElse:有值走第一支,空走第二支,一次表达完整
currentSession().ifPresentOrElse(
session -> System.out.println("resume: " + session),
() -> System.out.println("no session, prompting login"));
// 对比旧写法:isPresent + get 拆成两句,漏一句就出 bug
Optional<String> session = currentSession();
if (session.isPresent()) {
System.out.println("old style: " + session.get());
} else {
System.out.println("old style: login prompt");
}
// 有值场景:同一调用立刻切换分支
Optional.of("s-123").ifPresentOrElse(
s -> System.out.println("resume: " + s),
() -> System.out.println("unreachable here"));
}
}What the code does
The working surface is the class SessionRouter and the functions currentSession and main — everything else is wiring.
Optional wraps the possibly-absent value instead of a null sentinel.
Applying it
The main signature reads static Optional<String> currentSession()
The demo output is labeled (resume:, no session, prompting login, old style:), so every printed line maps back to its originating operation.
The sequence currentSession lives in main; running the file triggers it.
Statements that matter
return Optional.empty();
Optional<String> session = currentSession();
Optional.of("s-123").ifPresentOrElse(
s -> System.out.println("resume: " + s),
() -> System.out.println("unreachable here"));
Interactive Tools for This Topic
Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Optional ifPresentOrElse Branch print when run?
- Run it as a complete program — the output lines carry labels such as `resume:`, `no session, prompting login`, `old style:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.