TExcelTAD
Home › Java › Java Optional

Java Optional

null has caused more crashes than almost anything else in Java — Tony Hoare, who invented null references, called them his "billion-dollar mistake". When a method might not have a result (searching for a user who may not exist, the maximum of an empty list), returning null forces every caller to remember a check. Optional<T> (Java 8+) makes the possibility of "no value" explicit in the type.

An Optional is a small container that is either:

  • present — it holds exactly one non-null value, or
  • empty — it holds nothing.

Creating Optionals

java · try it yourself
import java.util.Optional;

class Main {
    public static void main(String[] args) {
        Optional<String> some = Optional.of("coffee");
        Optional<String> none = Optional.empty();
        String maybeNull = null;
        Optional<String> fromNullable = Optional.ofNullable(maybeNull);

        System.out.println(some);
        System.out.println(none);
        System.out.println(fromNullable.isPresent());
        System.out.println(some.isPresent() + " " + none.isEmpty());
    }
}
Optional[coffee]
Optional.empty
false
true true
Factory Use when
Optional.of(value) the value is definitely not null (throws if it is)
Optional.ofNullable(value) the value might be null
Optional.empty() there is no value

Returning an Optional

The typical place for Optional is a method's return type:

java · try it yourself
import java.util.List;
import java.util.Optional;

record User(int id, String name, String email) { }

class Main {
    static final List<User> USERS = List.of(
        new User(1, "Ada", "ada@example.com"),
        new User(2, "Linus", null));

    static Optional<User> findById(int id) {
        for (User u : USERS) {
            if (u.id() == id) return Optional.of(u);
        }
        return Optional.empty();
    }

    public static void main(String[] args) {
        Optional<User> found = findById(1);
        Optional<User> missing = findById(99);

        System.out.println(found.map(User::name).orElse("unknown"));
        System.out.println(missing.map(User::name).orElse("unknown"));
        found.ifPresent(u -> System.out.println("Hello, " + u.name()));
        missing.ifPresentOrElse(
            u -> System.out.println("Hello, " + u.name()),
            () -> System.out.println("No user with id 99"));
    }
}
Ada
unknown
Hello, Ada
No user with id 99

The caller can't forget that the user might be missing — the type says so.

Getting the value out

Method Returns when empty
orElse(other) other
orElseGet(supplier) the supplier's result (computed only if needed)
orElseThrow() throws NoSuchElementException
orElseThrow(supplier) throws the exception you provide
get() throws — avoid, prefer orElseThrow()
java · try it yourself
import java.util.Optional;

class Main {
    static String expensiveDefault() {
        System.out.println("  (computing default)");
        return "guest";
    }

    public static void main(String[] args) {
        Optional<String> name = Optional.of("Mia");
        Optional<String> empty = Optional.empty();

        System.out.println("orElse:");
        System.out.println(name.orElse(expensiveDefault()));      // default computed anyway!
        System.out.println("orElseGet:");
        System.out.println(name.orElseGet(Main::expensiveDefault)); // not computed
        System.out.println(empty.orElseGet(Main::expensiveDefault));

        try {
            empty.orElseThrow(() -> new IllegalStateException("name required"));
        } catch (IllegalStateException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
orElse:
  (computing default)
Mia
orElseGet:
Mia
  (computing default)
guest
Error: name required

Transforming: map, filter, flatMap

You can chain operations on an Optional without ever checking for null. If the Optional is empty at any step, the rest of the chain is skipped:

java · try it yourself
import java.util.Optional;

record Address(String city) { }
record Customer(String name, Address address) { }   // address may be null

class Main {
    static String cityOf(Customer c) {
        return Optional.ofNullable(c.address())
                .map(Address::city)
                .filter(city -> !city.isBlank())
                .map(String::toUpperCase)
                .orElse("NO CITY");
    }

    public static void main(String[] args) {
        Customer a = new Customer("Ada", new Address("London"));
        Customer b = new Customer("Ben", null);
        Customer c = new Customer("Cy", new Address("  "));
        System.out.println(cityOf(a));
        System.out.println(cityOf(b));
        System.out.println(cityOf(c));

        Optional<String> text = Optional.of("42");
        Optional<Integer> number = text.flatMap(Main::parse);
        System.out.println(number);
        System.out.println(Optional.of("x1").flatMap(Main::parse));
    }

    static Optional<Integer> parse(String s) {
        try {
            return Optional.of(Integer.parseInt(s));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }
}
LONDON
NO CITY
NO CITY
Optional[42]
Optional.empty

Use flatMap when the function itself returns an Optional, to avoid ending up with Optional<Optional<T>>.

Optionals from streams

Several stream operations return Optionals because the stream might be empty:

java · try it yourself
import java.util.List;

class Main {
    public static void main(String[] args) {
        List<Integer> scores = List.of(71, 94, 88);
        List<Integer> none = List.of();

        System.out.println(scores.stream().max(Integer::compare));
        System.out.println(none.stream().max(Integer::compare));
        System.out.println(scores.stream().filter(s -> s > 90).findFirst().orElse(-1));
        System.out.println(none.stream().mapToInt(i -> i).average());
    }
}
Optional[94]
Optional.empty
94
OptionalDouble.empty

Good practice

  • Do use Optional as a return type for "might not exist" results.
  • Don't use it for fields, method parameters or collections — an empty list already means "nothing".
  • Never return null from a method whose return type is Optional.
  • Prefer map, orElse, ifPresent over isPresent() + get() pairs.

Test yourself

What does Optional.ofNullable(null) return?

  1. null
  2. An empty Optional
  3. It throws NullPointerException
  4. Optional[null]

What is the difference between orElse(x()) and orElseGet(() -> x())?

  1. None
  2. orElse always evaluates x(); orElseGet only when the Optional is empty
  3. orElseGet always evaluates x()
  4. orElse throws when empty

What does Optional.of("hi").map(String::length).orElse(0) return?

  1. "hi"
  2. 0
  3. 2
  4. Optional[2]