Java 9 filled the gaps: or supplies a fallback Optional, ifPresentOrElse handles both branches, and stream plugs into a pipeline.
Optional<String> primary = Optional.empty();
Optional<String> fallback = Optional.of("cache");
System.out.println("or = " + primary.or(() -> fallback).orElse("none"));
primary.ifPresentOrElse(
v -> System.out.println("present: " + v),
() -> System.out.println("ifPresentOrElse: nothing there"));
System.out.println("filter = " + Optional.of(4).filter(n -> n % 2 == 0).isPresent());
System.out.println("orElseGet = " + primary.orElseGet(() -> "computed lazily"));
or = cache
ifPresentOrElse: nothing there
filter = true
orElseGet = computed lazily
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30