Library contents

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

  1. Start with An empty optional string
  2. Do this Use the fallback "A"
  3. Result A
With no stored value to transform, the optional supplies the fallback.

Syntax

Java 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.java

Normalize 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.

First output lineAda
Main.java
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);
        }
    }
}
Output
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.

Advertisements

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?

Giventripod missing · default 7 days
Worked result7

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?

Givenchoir → Hall · default Studio
Worked resultHall

What to watch for

An empty string can still be present in Optional. Filter it when an empty name should use the fallback.

Documentation for Optional.map and orElse