Stop 09 · Lambdas & StreamsTopics · 6/7

Optional

Part of the Java Roadmap

In short

NullPointerException is the most common crash in Java. Optional makes 'there might be no answer' part of a method's return type, so callers are forced to think about the empty case.

Optional<T> is a container that may or may not hold a value. It makes 'no result' explicit for return values and encourages handling it with orElse, orElseThrow, map and ifPresent.

The jaadu carefully lifts the lid of a wrapped gift box and peeks inside, holding a backup present behind its back.

Think of it like this

The gift box that might be empty

Your cousin hands you a wrapped box at Diwali. It might hold a watch, or it might be a joke and be empty. You don't put it on your wrist straight away. You check first, and decide what to do either way. Optional is that box around a return value.

Watch it happen

Returning null vs returning Optional

Return null

  • Signature hides that the result may be missing
  • Callers forget the null check
  • Crash appears far from the real cause
  • if (x != null) checks everywhere

Return Optional<T>

  • Signature says 'maybe no value'
  • orElse, orElseThrow and ifPresent handle both cases
  • map chains steps without null checks
  • Empty case is decided at one clear spot

Use Optional as a return type for lookups that can fail. Don't use it for fields, parameters or collections.

The big ideas

What you need to know

Creating one

Optional.of(x) for a value that is never null, Optional.ofNullable(x) when it might be, Optional.empty() for nothing.

Getting the value out

orElse(default), orElseGet(() -> compute()), orElseThrow() or ifPresentOrElse(...). Avoid bare get().

Transform safely

map and filter work on the value only if it is there. An empty Optional just passes through.

Where not to use it

Not for fields, method parameters or wrapping lists. Return an empty list instead of Optional<List>.

See it in code

Walk through the code

java
1import java.util.Map;2import java.util.NoSuchElementException;3import java.util.Optional;4 5public class OptionalDemo {6    record Customer(String name, String email) {}7 8    static Optional<Customer> findByPhone(Map<String, Customer> db, String phone) {9        return Optional.ofNullable(db.get(phone));10    }11 12    public static void main(String[] args) {13        Map<String, Customer> db = Map.of(14            "9876543210", new Customer("Priya", "priya@example.com"));15 16        String greeting = findByPhone(db, "9876543210")17                .map(Customer::name)18                .map(name -> "Welcome back, " + name)19                .orElse("Welcome, new customer");20 21        findByPhone(db, "9000000000").ifPresentOrElse(22                c -> System.out.println("Found " + c.name()),23                () -> System.out.println("No account yet"));24 25        Customer c = findByPhone(db, "9876543210")26                .orElseThrow(() -> new NoSuchElementException("Unknown phone"));27        System.out.println(greeting + " / " + c.email());28    }29}

1/4Map.get returns null for a missing key, so ofNullable wraps it safely.

A phone number lookup that returns Optional<Customer>, handled three different ways.

Save yourself the pain

Common mistakes

Oops

optional.get() without checking.

Do this instead

get() throws NoSuchElementException when empty. Use orElse, orElseThrow or ifPresent instead.

Oops

orElse(loadDefaultFromDatabase())

Do this instead

orElse always evaluates its argument, even when a value exists. Use orElseGet(() -> loadDefaultFromDatabase()) for costly defaults.

Oops

Returning null from a method declared to return Optional.

Do this instead

Return Optional.empty(). A null Optional defeats the whole point.

Your mission

Null-proof lookups

~20 min

Quick check

Optional<String> name = Optional.empty(); What does name.map(String::length).orElse(0) return?

Go deeper

  1. 1Return Optional from a findById method instead of null.
  2. 2Use orElseThrow() to fail with a clear exception.
  3. 3Avoid using Optional for fields or method parameters.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge