Optional

Optional represents a result that may be present or absent. It is especially useful as a return type for searches.

Optional methods keep the present and absent cases explicit:

MethodPurpose
map(function)Transform a present value
orElse(value)Use a ready fallback value
orElseGet(supplier)Create a fallback only when needed, from a no-argument lambda such as () -> "guest"
orElseThrow()Throw when the value is absent

Handle present or absent

import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        String nickname = null;
        String greeting = Optional.ofNullable(nickname)
            .map(String::toUpperCase)
            .map(name -> "Hello, " + name)
            .orElse("Hello, guest");
        System.out.println(greeting);
    }
}

Output:

Hello, guest

ofNullable turns null into an empty Optional. Because there is no nickname, both map calls are skipped and orElse supplies the greeting.

Find the first match

Streams produce Optionals too. The terminal operation findFirst returns an Optional holding the stream's first element, or an empty one when nothing survived the pipeline:

import java.util.List;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        List<String> cities = List.of(
                "Lima", "Oslo", "Lyon");
        Optional<String> first = cities.stream()
            .filter(city -> city.startsWith("L"))
            .findFirst();
        System.out.println(first);

        String missing = cities.stream()
            .filter(city -> city.startsWith("Z"))
            .findFirst()
            .orElse("none");
        System.out.println(missing);
    }
}

Output:

Optional[Lima]
none

Two cities start with L, and findFirst keeps the first one. No city starts with Z, so the second Optional is empty and orElse supplies the fallback.

Do not call get without proving a value exists. Prefer orElse, orElseGet, orElseThrow, or conditional methods.

Find the first matching color, uppercase it, or use NONE when no color matches.