Java: Chain Optional with map and filter

Optional.map and filter transform a value only when it is present and matches.

Code
Optional<String> name = Optional.of("  Ava  ");
String result = name.map(String::strip)
        .filter(s -> s.length() > 2)
        .map(String::toUpperCase)
        .orElse("N/A");
System.out.println(result);
Output
AVA
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-26