Java Optional.map and orElse
Optional represents a value that may be present or absent. Map a present name to its display form, then supply a fallback for an absent result.
A simple example
Optional.map and orElse
- Start with An empty optional string
- Do this Use the fallback "A"
- Result A
Syntax
Optional.ofNullable(name).map(String::strip).filter(predicate).orElse(fallback)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaNormalize an optional display name
A profile form may omit a display name or supply a value containing extra space. Handle the missing case before applying text cleanup so an optional field does not interrupt registration.
import java.util.Optional;
class Main {
public static void main(String[] args) throws Exception {
for (String name : new String[]{" Ada ", " ", null}) {
String display = Optional.ofNullable(name).map(String::strip)
.filter(s -> !s.isEmpty()).orElse("guest");
System.out.println(display);
}
}
}
Ada guest guest
A blank string is initially present. Strip and filter before selecting the fallback so null and whitespace-only names are handled consistently.
Look up a borrowed tripod
The equipment desk has a two-day loan period for a camera, but no special period for a tripod. The system uses the recorded value when present and the displayed fallback otherwise. Which value reaches the screen?
Read a room preference
The timetable stores a room choice for the choir club. The system uses the recorded value when present and the displayed fallback otherwise. Which value reaches the screen?
What to watch for
An empty string can still be present in Optional. Filter it when an empty name should use the fallback.