Optional: or, ifPresentOrElse and stream

Java 9 filled the gaps: or supplies a fallback Optional, ifPresentOrElse handles both branches, and stream plugs into a pipeline.

Code
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"));
Output
or        = cache
ifPresentOrElse: nothing there
filter    = true
orElseGet = computed lazily
Advertisement

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