Optional models a value that may be absent, so you handle "missing" explicitly.
Map<String, Integer> ages = Map.of("ava", 30);
int age = Optional.ofNullable(ages.get("ben")).orElse(-1);
System.out.println("ben age = " + age);
Optional.ofNullable(ages.get("ava"))
.ifPresent(a -> System.out.println("ava age = " + a));
ben age = -1
ava age = 30
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