Optional

Optional is a container that holds one value or none, used as a return type to say "there may be no result" in a way the caller cannot overlook. This page explains what an Optional is and how its API grew from Java 8 to 11, then creates and unwraps Optionals, chains lookups through objects that may be missing, uses the Optionals that streams return, runs six traps, measures the cost, and lists where Optional does more harm than good.

Contents

What Optional is for

java.util.Optional<T> (Java 8) is a small final class with one field: a reference to the value, or null when the Optional is empty. All empty Optionals are one shared instance. Its purpose is narrow and deliberate: to be the return type of a method that may legitimately have no result, such as a search. A method that returns String may return null without the caller noticing; a method that returns Optional<String> forces the caller to decide what happens when there is nothing.

Optional is a value-based class: instances that are equals are interchangeable, and code must not depend on their identity, synchronize on them or compare them with ==. It is also not Serializable, by design, which is one sign that it was never meant for fields.

The Optional API by version
MethodSinceWhat it doesBest for
of, ofNullable, emptyJava 8Create: of rejects null, ofNullable maps null to emptyWrapping a result in the method that returns it
orElse, orElseGet, orElseThrow(supplier)Java 8Unwrap with a default, a computed default or an exceptionThe end of a chain
map, flatMap, filterJava 8Transform or test the value only if presentChaining lookups
ifPresentJava 8Run an action if presentSide effects
ifPresentOrElse, or, streamJava 9Both branches; a fallback Optional; zero or one element streamFallback lookups, flattening
orElseThrow()Java 10Like get(), with a name that says it can throwWhen empty is a bug
isEmptyJava 11The opposite of isPresentReadable conditions

OptionalInt, OptionalLong and OptionalDouble hold primitives without boxing, but have no map, flatMap or filter. The examples ran on JDK 21.

Creating and unwrapping

A lookup in a small map of user emails returns an Optional. User 1 has an address, user 2 has a blank one, and user 9 does not exist, so every branch of the API gets used.

Java
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;

public class OptionalBasics {

    static final Map<Integer, String> EMAILS = Map.of(1, "ada@example.com", 2, "  ");

    // Return Optional when "no result" is a normal outcome
    static Optional<String> findEmail(int userId) {
        return Optional.ofNullable(EMAILS.get(userId));
    }

    public static void main(String[] args) {
        System.out.println("found:   " + findEmail(1));
        System.out.println("missing: " + findEmail(9));

        // Getting the value out
        System.out.println("orElse:        " + findEmail(9).orElse("no email"));
        System.out.println("orElseGet:     " + findEmail(9).orElseGet(() -> "computed default"));
        try {
            findEmail(9).orElseThrow(() -> new IllegalArgumentException("user 9 has no email"));
        } catch (IllegalArgumentException e) {
            System.out.println("orElseThrow:   " + e.getMessage());
        }
        findEmail(1).ifPresentOrElse(
                e -> System.out.println("ifPresent:     send to " + e),
                () -> System.out.println("ifPresent:     nothing to send"));

        // Transforming without unwrapping
        String domain = findEmail(1)
                .map(e -> e.substring(e.indexOf('@') + 1))
                .orElse("?");
        System.out.println("map:           " + domain);
        System.out.println("filter blank:  " + findEmail(2).filter(e -> !e.isBlank()).isPresent());

        // Java 9 to 11 additions
        System.out.println("or (Java 9):   " + findEmail(9).or(() -> findEmail(1)).orElseThrow());
        System.out.println("isEmpty (11):  " + findEmail(9).isEmpty());
        try {
            findEmail(9).orElseThrow();                     // Java 10: same as get()
        } catch (NoSuchElementException e) {
            System.out.println("orElseThrow(): NoSuchElementException: " + e.getMessage());
        }

        // Optional.of(null) fails immediately
        try {
            Optional.of(EMAILS.get(9));
        } catch (NullPointerException e) {
            System.out.println("Optional.of(null): NullPointerException");
        }
    }
}

Output:

Output
found:   Optional[ada@example.com]
missing: Optional.empty
orElse:        no email
orElseGet:     computed default
orElseThrow:   user 9 has no email
ifPresent:     send to ada@example.com
map:           example.com
filter blank:  false
or (Java 9):   ada@example.com
isEmpty (11):  true
orElseThrow(): NoSuchElementException: No value present
Optional.of(null): NullPointerException
  • ofNullable turned the missing map entry into Optional.empty; of(null) threw NullPointerException at once. Use of only when null would be a bug.
  • The three ways out of an empty Optional gave a constant default, a computed default and an exception with a useful message. orElseThrow() with no argument (Java 10) throws NoSuchElementException with the message "No value present", which is what get() does; the newer name makes the risk visible at the call site.
  • map extracted the domain without unwrapping, and filter turned the blank address into an empty Optional, so "user has a usable email" became one expression.
  • or (Java 9) tried a second lookup when the first was empty. Unlike orElse, it keeps the result wrapped, so it can be chained further.

Chaining lookups with map and flatMap

An order has a customer, who may have an address, which has a city. Order 1 has everything, order 2's customer has no address, and order 3 does not exist, which covers each place the chain can stop.

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

public class OptionalChains {

    record Address(String city) {
    }

    // The field may be null; the accessor wraps it, so callers cannot forget the check
    record Customer(String name, Address address) {
        Optional<Address> findAddress() {
            return Optional.ofNullable(address);
        }
    }

    record Order(int id, Customer customer) {
    }

    static Optional<Order> findOrder(int id, List<Order> orders) {
        return orders.stream().filter(o -> o.id() == id).findFirst();
    }

    static String expensiveDefault() {
        System.out.println("    (expensiveDefault was called)");
        return "unknown";
    }

    public static void main(String[] args) {
        List<Order> orders = List.of(
                new Order(1, new Customer("ann", new Address("Lyon"))),
                new Order(2, new Customer("bob", null)));

        for (int id : new int[] {1, 2, 3}) {
            // flatMap: findAddress returns an Optional, so map would nest Optional<Optional<..>>
            String city = findOrder(id, orders)
                    .map(Order::customer)
                    .flatMap(Customer::findAddress)
                    .map(Address::city)
                    .orElse("no city");
            System.out.println("order " + id + ": " + city);
        }

        // orElse evaluates its argument even when a value is present; orElseGet does not
        System.out.println("orElse with a value present:");
        findOrder(1, orders).map(o -> o.customer().name()).orElse(expensiveDefault());
        System.out.println("orElseGet with a value present:");
        findOrder(1, orders).map(o -> o.customer().name())
                .orElseGet(OptionalChains::expensiveDefault);

        // Optional to stream: keep only present values
        List<String> cities = orders.stream()
                .map(o -> o.customer().findAddress())
                .flatMap(Optional::stream)
                .map(Address::city)
                .toList();
        System.out.println("known cities: " + cities);
    }
}

Output:

Output
order 1: Lyon
order 2: no city
order 3: no city
orElse with a value present:
    (expensiveDefault was called)
orElseGet with a value present:
known cities: [Lyon]
  • One chain replaced three nested null checks. Each step runs only if the previous one produced a value, and any missing link ends with "no city".
  • findAddress already returns an Optional, so the chain uses flatMap. With map, the result would be Optional<Optional<Address>>. The rule is the same as for streams: map for a plain function, flatMap for a function that returns the wrapper type.
  • orElse(expensiveDefault()) called expensiveDefault even though a value was present, because Java evaluates method arguments before the call. orElseGet takes a supplier and called it only when needed, which here was never. Use orElse for constants and orElseGet for anything that costs something or has side effects.
  • flatMap(Optional::stream) (Java 9) dropped the orders without an address and kept the city of the one that had one.

Optional in streams

Stream operations that may find nothing return an Optional, and primitive streams return the primitive variants. The program runs each kind on a short price list and on an empty one.

Java
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class StreamOptionals {

    record Item(String name, int price) { }

    public static void main(String[] args) {
        List<Item> items = List.of(new Item("pen", 2), new Item("book", 12), new Item("bag", 30));
        List<Item> none = List.of();

        // Terminal operations that may find nothing return Optional
        Optional<Item> firstExpensive = items.stream().filter(i -> i.price() > 10).findFirst();
        Optional<Item> cheapest = items.stream().min(Comparator.comparingInt(Item::price));
        Optional<Integer> total = items.stream().map(Item::price).reduce(Integer::sum);
        System.out.println("findFirst price > 10: " + firstExpensive.map(Item::name).orElse("-"));
        System.out.println("min by price:         " + cheapest.map(Item::name).orElse("-"));
        System.out.println("reduce sum:           " + total.orElse(0));
        System.out.println("max of empty list:    "
                + none.stream().max(Comparator.comparingInt(Item::price)));

        // Primitive streams use OptionalInt, OptionalLong, OptionalDouble
        OptionalInt maxPrice = items.stream().mapToInt(Item::price).max();
        OptionalDouble avg = IntStream.empty().average();
        System.out.println("max price:            " + maxPrice.getAsInt());
        System.out.println("average of nothing:   " + avg + ", orElse " + avg.orElse(Double.NaN));

        // Collectors.maxBy wraps the result per group
        var byCheapness = items.stream().collect(Collectors.partitioningBy(i -> i.price() < 20,
                Collectors.maxBy(Comparator.comparingInt(Item::price))));
        System.out.println("most expensive under 20: " + byCheapness.get(true).map(Item::name)
                .orElse("-"));

        // Optional.stream (Java 9): flatten a list of Optionals
        List<Optional<String>> lookups = List.of(Optional.of("a"), Optional.empty(),
                Optional.of("c"));
        System.out.println("present values:       " + lookups.stream().flatMap(Optional::stream)
                .toList());
    }
}

Output:

Output
findFirst price > 10: book
min by price:         pen
reduce sum:           44
max of empty list:    Optional.empty
max price:            30
average of nothing:   OptionalDouble.empty, orElse NaN
most expensive under 20: book
present values:       [a, c]
  • findFirst, min, max and the one-argument reduce return Optional, because an empty stream has no first element, no minimum and no sum without an identity value. The max of the empty list was Optional.empty rather than an exception or a null.
  • IntStream.max returned an OptionalInt, read with getAsInt(). The average of an empty stream is OptionalDouble.empty, not 0 and not NaN, so the program chose NaN explicitly.
  • Collectors.maxBy inside partitioningBy produced an Optional per group, because a group could be empty.
  • A list of Optionals is usually a sign that the code should have filtered earlier, but when you get one, flatMap(Optional::stream) keeps the present values.

Six Optional traps

Optional removes the most common null bug, but it brings its own. Each trap below runs and prints what happens.

Java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class OptionalTraps {

    static Optional<String> badFind(String key) {
        return null;                                    // a method returning Optional... null
    }

    public static void main(String[] args) throws IOException {
        // 1. map() turns a null result into an empty Optional, silently
        Map<String, String> phones = new HashMap<>();
        phones.put("ann", null);
        Optional<String> phone = Optional.of("ann").map(phones::get);
        System.out.println("1. map to a null result: " + phone);

        // 2. get() on an empty Optional is no better than a null dereference
        try {
            Optional.empty().get();
        } catch (RuntimeException e) {
            System.out.println("2. get() on empty: " + e.getClass().getSimpleName()
                    + ": " + e.getMessage());
        }

        // 3. An Optional reference can itself be null
        try {
            badFind("x").isPresent();
        } catch (NullPointerException e) {
            System.out.println("3. method returned null instead of Optional.empty(): NPE");
        }

        // 4. equals compares contents; == is unreliable on a value-based class
        Optional<String> a = Optional.of("x");
        Optional<String> b = Optional.of("x");
        System.out.println("4. equals " + a.equals(b) + ", == " + (a == b)
                + ", empty() == empty() " + (Optional.empty() == Optional.empty()));

        // 5. Optional is not Serializable, so it breaks serializable fields
        try (ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream())) {
            out.writeObject(Optional.of("x"));
        } catch (NotSerializableException e) {
            System.out.println("5. serializing: NotSerializableException " + e.getMessage());
        }

        // 6. orElse(null) brings the null straight back
        String fallback = Optional.<String>empty().orElse(null);
        System.out.println("6. orElse(null) gives " + fallback);
    }
}

Output:

Output
1. map to a null result: Optional.empty
2. get() on empty: NoSuchElementException: No value present
3. method returned null instead of Optional.empty(): NPE
4. equals true, == false, empty() == empty() true
5. serializing: NotSerializableException java.util.Optional
6. orElse(null) gives null
  1. map wraps its function's result with ofNullable, so a function that returns null silently produces an empty Optional. Here "ann" exists but her phone entry is null, and the result looks the same as "no such person". If the difference matters, check it before mapping.
  2. get() on an empty Optional throws NoSuchElementException. Calling get() after an isPresent() check is just a null check with more code; prefer orElse, map or ifPresent.
  3. A method declared to return Optional returned null, and the caller's isPresent() threw NullPointerException. Never return null from such a method; return Optional.empty().
  4. Two Optionals of "x" are equals but not ==, while the shared empty instance happens to be == to itself. Because Optional is value-based, identity comparisons are meaningless; always use equals.
  5. Writing an Optional with ObjectOutputStream threw NotSerializableException. A serializable class with an Optional field cannot be serialized, which is one reason Optional fields are discouraged.
  6. orElse(null) is allowed and returns plain null. It is sometimes needed at the boundary with older APIs, but inside new code it throws away the point of the Optional.

What Optional costs

An Optional is an object, so wrapping every result allocates. The program looks up 50 million names, a quarter of them missing, once with a plain null check and once with ofNullable(...).map(String::length).orElse(0). Best of 3 runs, a rough comparison.

Java
import java.util.Optional;

public class OptionalCost {

    static final String[] NAMES = new String[1024];

    static {
        for (int i = 0; i < NAMES.length; i++) {
            NAMES[i] = i % 4 == 0 ? null : "name" + i;      // a quarter are missing
        }
    }

    static int withNullCheck(int i) {
        String s = NAMES[i & 1023];
        return s != null ? s.length() : 0;
    }

    static int withOptional(int i) {
        return Optional.ofNullable(NAMES[i & 1023]).map(String::length).orElse(0);
    }

    public static void main(String[] args) {
        int n = 50000000;
        long bestNull = Long.MAX_VALUE;
        long bestOpt = Long.MAX_VALUE;
        long a = 0;
        long b = 0;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            a = 0;
            for (int i = 0; i < n; i++) {
                a += withNullCheck(i);
            }
            bestNull = Math.min(bestNull, System.nanoTime() - t0);
            t0 = System.nanoTime();
            b = 0;
            for (int i = 0; i < n; i++) {
                b += withOptional(i);
            }
            bestOpt = Math.min(bestOpt, System.nanoTime() - t0);
        }
        System.out.println("same result: " + (a == b));
        System.out.printf("null check: %,4d ms%n", bestNull / 1000000);
        System.out.printf("Optional:   %,4d ms%n", bestOpt / 1000000);
    }
}

Output (2-CPU Linux machine, JDK 21, best of 3):

Output
same result: true
null check:   32 ms
Optional:    273 ms
  • Both versions computed the same total, and the Optional version was several times slower in this tight loop. Each call can allocate an Optional for the name and another for the mapped length, and the JIT's escape analysis does not always remove them.
  • In absolute terms the cost is a few nanoseconds per call. For a method called once per request, or once per database row, it is irrelevant. For the inner loop of a numeric algorithm, a null check or a sentinel value is the better choice.
  • As a field, an Optional adds an object of about 16 bytes per instance on a 64-bit JVM with compressed pointers, on top of the reference to it.

Where to use Optional, and where not

Optional guidelines
UseRecommendation
Return type of a lookup that may find nothingYes, this is its purpose
Return type of a method returning a collectionNo: return an empty collection
Field of a classNo: use a nullable field, and an accessor that returns Optional if useful
Method or constructor parameterNo: overload the method, or accept null and document it
Element of a collection or value in a mapNo: leave the element out instead
Hot numeric loopsNo: use a null check, a sentinel, or OptionalInt
Ending a chainorElse for constants, orElseGet for computed values, orElseThrow when empty is an error
Bridging to code that expects nullorElse(null), at the boundary only

Other tools also handle a missing value, and are often shorter. When you only need a default for a possibly null reference, Objects.requireNonNullElse(value, fallback) and requireNonNullElseGet (both Java 9) do it without a wrapper. For maps, getOrDefault and computeIfAbsent avoid the null in the first place. When migrating an older API that returns null, add a new method that returns Optional, such as findUser next to getUser, rather than changing the return type of the old one, which would break every caller at once.

Related pages: streams, where most Optionals come from, functional interfaces for the functions passed to map, and filtering and finding in a list.