Tutorials / Java: From Zero to Advanced / Optional: handling missing values

Optional: handling missing values

13 min read java
Course contents (20 lessons)
  1. Getting started
  2. Installing JDK 21 and running Java code
  3. Your first program: how a Java file is built
  4. Language basics
  5. Variables and data types
  6. Strings, formatting and text blocks
  7. Control flow: if, switch expressions and loops
  8. Data and methods
  9. Arrays and the collections framework
  10. Methods, overloading and varargs
  11. Object-oriented Java
  12. Classes, objects and encapsulation
  13. Inheritance, abstract classes and interfaces
  14. Records, enums and sealed types
  15. Writing robust code
  16. Exceptions: checked, unchecked and try-with-resources
  17. Generics, bounded types and wildcards
  18. Files and the NIO.2 API
  19. Modern Java
  20. Lambdas and the Stream API
  21. Optional: handling missing values
  22. Concurrency: executors, CompletableFuture and virtual threads
  23. Tools, services and the final project
  24. Maven and Gradle basics
  25. Testing with JUnit 5
  26. A small REST service with the JDK HTTP server
  27. Final project: a library manager

The billion-dollar mistake in Java

Null is a value that means "nothing here". Calling a method on it throws NullPointerException, and every Java developer meets this exception hundreds of times. The deeper problem is that the type does not tell you whether a method may return null. You find out in production.

Java 8 added Optional<T>, a small container that holds either one value or nothing. When a method returns Optional<User>, the signature itself tells the caller: this may be empty, deal with it.

Creating and using an Optional

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

public class Main {

    record Address(String city) {}
    record User(String name, String email, Address address) {}

    static final Map<Integer, User> USERS = Map.of(
            1, new User("Ayesha", "ayesha@example.com", new Address("Lahore")),
            2, new User("Bilal", null, null));

    static Optional<User> findUser(int id) {
        return Optional.ofNullable(USERS.get(id));
    }

    static Optional<String> email(User user) {
        return Optional.ofNullable(user.email());
    }

    static Optional<Address> address(User user) {
        return Optional.ofNullable(user.address());
    }

    public static void main(String[] args) {
        // Three ways to create one
        Optional<String> empty = Optional.empty();
        Optional<String> present = Optional.of("value");        // throws if the argument is null
        Optional<String> maybe = Optional.ofNullable(null);     // empty if null
        System.out.println(empty + " " + present + " " + maybe);

        // Reading the value safely
        System.out.println(findUser(1).map(User::name).orElse("unknown"));
        System.out.println(findUser(99).map(User::name).orElse("unknown"));

        // orElse always evaluates its argument; orElseGet only when needed
        String lazy = findUser(1).map(User::name).orElseGet(() -> expensiveDefault());
        System.out.println(lazy);

        // orElseThrow for "must exist"
        try {
            findUser(99).orElseThrow(() -> new NoSuchElementException("User 99 not found"));
        } catch (NoSuchElementException e) {
            System.out.println(e.getMessage());
        }

        // ifPresent and ifPresentOrElse
        findUser(2).ifPresent(u -> System.out.println("Found " + u.name()));
        findUser(2).flatMap(Main::email).ifPresentOrElse(
                e -> System.out.println("Email: " + e),
                () -> System.out.println("Bilal has no email"));

        // Chaining with flatMap avoids nested null checks
        String city = findUser(1)
                .flatMap(Main::address)
                .map(Address::city)
                .orElse("no address");
        System.out.println(city);

        String city2 = findUser(2)
                .flatMap(Main::address)
                .map(Address::city)
                .orElse("no address");
        System.out.println(city2);

        // filter keeps the value only if the predicate is true
        Optional<String> longEmail = findUser(1).flatMap(Main::email).filter(e -> e.length() > 30);
        System.out.println(longEmail.isPresent());

        // Streams of Optionals
        long withEmail = List.of(1, 2, 99).stream()
                .map(Main::findUser)
                .flatMap(Optional::stream)
                .filter(u -> u.email() != null)
                .count();
        System.out.println("Users with email: " + withEmail);
    }

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

Walking through it

There are three factory methods. Optional.empty() is an empty one. Optional.of(x) wraps a value and throws NullPointerException if x is null, which is useful when null would be a bug. Optional.ofNullable(x) turns null into empty, and it is the one you use when wrapping values that come from old code. findUser does exactly that with a map lookup.

The main idea is to avoid get(). The method get() throws NoSuchElementException when empty, so calling it without a check just moves the null problem. Use one of the safer ways to unwrap.

  • orElse(x) gives a fixed fallback.
  • orElseGet(supplier) computes the fallback only when needed. In the example, the "(computing a default)" line never prints, because the user exists. With orElse(expensiveDefault()), it would be computed every time, even when unused. Use orElseGet when the default costs something.
  • orElseThrow(supplier) is the right choice when absence is an error. Since Java 10, there is also a no-argument orElseThrow().
  • ifPresent and ifPresentOrElse run code for the present or empty case.

The chain with map and flatMap is where Optional pays off. map transforms the value if there is one, and the result is wrapped again. flatMap is for functions that already return an Optional, so you do not end up with Optional<Optional<...>>. Look at the city lookup. Without Optional, it would need a null check for the user, one for the address and one for the city. With it, the same logic is one readable pipeline, and a missing link anywhere gives the fallback "no address".

filter turns a present value into empty if the predicate fails. Optional.stream(), added in Java 9, turns an Optional into a stream of zero or one elements, which is neat for dropping the empty ones with flatMap.

Where Optional does not belong

  • Fields. Optional is not serialisable and adds an extra object. Keep a nullable field, or model the absence in another way.
  • Method parameters. Callers then have to wrap values. Use overloads, or accept null with a clear contract.
  • Collections. Return an empty list instead of Optional<List<T>>.
  • Everywhere else. It is designed mainly as a return type for methods that may have no result.

Also, never return null from a method that returns Optional. It defeats the whole idea.

Common mistakes

  • Calling get() without isPresent(). And then if (opt.isPresent()) opt.get() is just a clumsy null check. Prefer map, orElse and friends.
  • Using orElse with an expensive call. Use orElseGet.
  • Using Optional.of on a value that may be null.
  • Using Optional for fields and parameters.
  • Using map where flatMap is needed, and getting a nested Optional.

Try it yourself

  1. Write Optional<Integer> parse(String text) that returns empty for non-numbers instead of throwing.
  2. Write a method that returns the longest word in a list as an Optional, empty for an empty list.
  3. Extend the example with a Company record and a user-to-company-to-country chain using flatMap.
java
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;

public class Main {

    record Address(String city) {}
    record User(String name, String email, Address address) {}

    static final Map<Integer, User> USERS = Map.of(
            1, new User("Ayesha", "ayesha@example.com", new Address("Lahore")),
            2, new User("Bilal", null, null));

    static Optional<User> findUser(int id) {
        return Optional.ofNullable(USERS.get(id));
    }

    static Optional<String> email(User user) {
        return Optional.ofNullable(user.email());
    }

    static Optional<Address> address(User user) {
        return Optional.ofNullable(user.address());
    }

    public static void main(String[] args) {
        // Three ways to create one
        Optional<String> empty = Optional.empty();
        Optional<String> present = Optional.of("value");        // throws if the argument is null
        Optional<String> maybe = Optional.ofNullable(null);     // empty if null
        System.out.println(empty + " " + present + " " + maybe);

        // Reading the value safely
        System.out.println(findUser(1).map(User::name).orElse("unknown"));
        System.out.println(findUser(99).map(User::name).orElse("unknown"));

        // orElse always evaluates its argument; orElseGet only when needed
        String lazy = findUser(1).map(User::name).orElseGet(() -> expensiveDefault());
        System.out.println(lazy);

        // orElseThrow for "must exist"
        try {
            findUser(99).orElseThrow(() -> new NoSuchElementException("User 99 not found"));
        } catch (NoSuchElementException e) {
            System.out.println(e.getMessage());
        }

        // ifPresent and ifPresentOrElse
        findUser(2).ifPresent(u -> System.out.println("Found " + u.name()));
        findUser(2).flatMap(Main::email).ifPresentOrElse(
                e -> System.out.println("Email: " + e),
                () -> System.out.println("Bilal has no email"));

        // Chaining with flatMap avoids nested null checks
        String city = findUser(1)
                .flatMap(Main::address)
                .map(Address::city)
                .orElse("no address");
        System.out.println(city);

        String city2 = findUser(2)
                .flatMap(Main::address)
                .map(Address::city)
                .orElse("no address");
        System.out.println(city2);

        // filter keeps the value only if the predicate is true
        Optional<String> longEmail = findUser(1).flatMap(Main::email).filter(e -> e.length() > 30);
        System.out.println(longEmail.isPresent());

        // Streams of Optionals
        long withEmail = List.of(1, 2, 99).stream()
                .map(Main::findUser)
                .flatMap(Optional::stream)
                .filter(u -> u.email() != null)
                .count();
        System.out.println("Users with email: " + withEmail);
    }

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

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account