Skip to content
Tutorials Center
My learning

Topics

Lesson 104 of 201 ยท Generics and Functional Programming

Optional

Learn Java Optional - creating it with of/empty/ofNullable, map, flatMap and filter, orElse vs orElseGet, orElseThrow, ifPresentOrElse and when not to use Optional.

null is Java's way of saying "there's no value here," and it's behind one of the most common crashes in Java programs: the NullPointerException. The trouble isn't null itself; it's that nothing in a method's signature tells you it might return null. String findEmail(int userId) looks like it always gives you a string, until one day it doesn't.

java.util.Optional<T> (Java 8) makes "maybe there's no value" visible in the type. A method returning Optional<String> tells every caller, and the compiler, that the result can be missing and must be handled. You've already seen it as the result of stream operations like findFirst and max in Streams. This lesson covers creating Optionals, getting values out safely, transforming them with map, flatMap and filter, the eager-evaluation trap of orElse, and the clear guidelines for when Optional helps and when it gets in the way.

A box that is either full or empty

An Optional<T> is a small, immutable container holding either one non-null value or nothing. There are three ways to make one:

Factory Result
Optional.of(value) A full Optional; throws NullPointerException if value is null
Optional.empty() An empty Optional
Optional.ofNullable(value) Full if value isn't null, otherwise empty

Use of when a null would be a bug (you want it to fail fast), and ofNullable to wrap values from code that may return null, such as Map.get.

Java Creating Optionals and checking them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

isEmpty() was added in Java 11 as the opposite of isPresent(). You'll rarely need either, though: the methods in the next sections handle both cases without an if.

Getting the value out

The whole point of Optional is that you decide what happens when the value is missing. Each method below answers that question differently:

Method When empty
orElse(fallback) Returns the fallback value
orElseGet(supplier) Calls the supplier and returns its result
orElseThrow() (Java 10) Throws NoSuchElementException
orElseThrow(supplier) Throws the exception you create
ifPresent(action) Does nothing
ifPresentOrElse(action, emptyAction) (Java 9) Runs the empty action
get() Throws NoSuchElementException (avoid it; see below)
Java orElse, orElseGet, orElseThrow and ifPresentOrElse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

orElseThrow() without arguments does the same as get(), but its name admits that it can throw. That's why modern code prefers it: get() looks safe, and calling it without checking is just a NullPointerException with a different name. Use orElseThrow() only when you know the value is there, for example right after a check that guarantees it.

orElse vs orElseGet: the eager trap

This is the Optional mistake that experienced developers still make. The argument of orElse is a normal method argument, so Java always evaluates it, even when the Optional is full and the fallback is thrown away. orElseGet takes a Supplier and only calls it when the value is missing.

Java orElse always evaluates its argument

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The default was computed once, by orElse, although nobody needed it. For constants and cheap values (orElse("Guest"), orElse(0)) that doesn't matter. If the fallback queries a database, creates objects, logs or has any side effect, use orElseGet.

Transforming: map, flatMap, filter and or

Optional has a small, stream-like API that lets you chain steps. Each step runs only if there is a value; an empty Optional simply passes through as empty.

  • map(f): applies f to the value and wraps the result. If f returns null, you get an empty Optional.
  • flatMap(f): for functions that already return an Optional, so you don't end up with Optional<Optional<T>>.
  • filter(predicate): keeps the value only if it matches; otherwise becomes empty.
  • or(supplier) (Java 9): if empty, tries another Optional-returning source.
  • stream() (Java 9): a stream of zero or one element, handy with flatMap in stream pipelines.
Java Chaining map, flatMap, filter and or

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Without Optional, postcodeOf would be a ladder of nested if (x != null) checks. Here each step says one thing, and the three different reasons for "no postcode" (unknown customer, no address, blank code) all collapse into one empty result.

Notice how Customer stores a plain, nullable field and offers an address() method that returns an Optional. That's the recommended shape: keep null inside the class and expose Optional at the boundary, as the guidelines below explain.

Primitive Optionals

To avoid boxing, there are OptionalInt, OptionalLong and OptionalDouble, returned by primitive streams: IntStream.max() gives an OptionalInt, and average() gives an OptionalDouble. They have getAsInt()/getAsDouble(), orElse, orElseGet, orElseThrow, ifPresent and ifPresentOrElse, but no map, flatMap or filter. Box them if you need those operations.

Java
OptionalDouble avg = IntStream.of(3, 4, 8).average();   // OptionalDouble[5.0]
double value = avg.orElse(0.0);

When to use Optional, and when not to

Optional was designed for one main job: a method's return type when "no result" is a normal outcome. Repositories (findById), lookups, parsing that may fail, and "find the first matching" methods are perfect fits. Beyond that, the guidelines most Java teams follow are:

Don't use Optional for:

  • Fields. Use a nullable field and return Optional.ofNullable(field) from the getter. Optional isn't Serializable and adds an object per field.
  • Method parameters. void send(Optional<String> cc) forces callers to wrap values; overload the method or accept a nullable parameter instead.
  • Collections. Return an empty list, not Optional<List<T>> or null. An empty collection already means "nothing."
  • Inside collections: List<Optional<T>> is almost always better as a filtered List<T>.
  • Replacing every null check. Optional.ofNullable(x).ifPresent(...) just to avoid if (x != null) is longer and slower.

A few more rules:

  • Never return null from a method declared to return Optional. That defeats the entire purpose; return Optional.empty().
  • Don't call isPresent() and then get(). That's a null check in disguise. Use map, orElse, ifPresentOrElse, or orElseThrow.
  • Don't compare Optionals with == or use them for synchronization; they are value-based classes. Use equals, which compares contents.

Here is a before/after of a typical refactoring:

Java From isPresent and get to a clean chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Both versions behave the same, but the second can't call get() on an empty Optional by accident, and it has no branches to get wrong.

Optional and null, together

Optional doesn't make null disappear from Java; it gives you a clear vocabulary at API boundaries. Inside a method, plain null checks and Objects.requireNonNull (see The Object Class) are still fine. At the edges, convert: wrap nullable results with Optional.ofNullable, and when calling old code that expects null, unwrap with optional.orElse(null). The broader strategy, including when to throw instead of returning empty, is covered in Exception Handling Best Practices.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Optional.ofNullable(null).map(String::valueOf).orElse("none") return?

    ofNullable(null) is empty, map is skipped on an empty Optional, and orElse returns the fallback "none".
  2. 2. Optional.of("x").orElse(load()) - when is load() called?

    orElse receives an already computed value, so load() runs even though its result is discarded. orElseGet(() -> load()) would skip it.
  3. 3. find(id) returns Optional<Customer> and Customer::email returns Optional<String>. Which gives an Optional<String>?

    map would produce Optional<Optional<String>>. flatMap is for functions that already return an Optional and flattens the result.
  4. 4. Which use of Optional follows common best practice?

    Optional is meant for return values where "no result" is normal. Fields, parameters and wrapped collections are discouraged.
  5. 5. What does Optional.of(" ").map(String::strip).filter(s -> !s.isEmpty()).isPresent() return?

    strip turns the blank string into an empty string, filter rejects it, and the Optional becomes empty, so isPresent is false.

Summary

  • Optional<T> holds one non-null value or nothing; it makes "may be missing" part of a method's return type.
  • Create with Optional.of (fails on null), Optional.empty() or Optional.ofNullable.
  • Get values with orElse, orElseGet, orElseThrow, ifPresent and ifPresentOrElse; avoid get() and isPresent() + get().
  • orElse always evaluates its argument; use orElseGet for costly or side-effecting defaults.
  • Chain with map, flatMap (for Optional-returning functions), filter, or and stream.
  • Use Optional mainly for return values; not for fields, parameters or collections, and never return null instead of Optional.empty().

Next: Functional Programming in Java, where you'll combine pure functions, immutability and composition into a coherent style.