← Writing

Java Optional: when to use orElseGet for a missing result

On this page

Return an Optional when a lookup can succeed without finding a match. The example returns Optional<String> for a buyer’s name. Use orElse for a ready-made default and orElseGet to compute a default only when the lookup is empty. Let lookup and validation failures surface as exceptions or explicit error results, and always return an Optional instance. Java SE 21 Optional.orElseGet

Creating an Optional with empty, of, and ofNullable

Use Optional.empty() for known absence and Optional.of(value) when the value is required. of(null) immediately throws NullPointerException. Use ofNullable(value) at a nullable boundary, such as the lookup below, where a legacy operation returns null for an unknown ID.

Checking and unwrapping with isPresent, isEmpty, and get

isPresent() is true when a value exists. Java 11’s isEmpty() gives the inverse. Calling get() after isPresent() works on the same instance. For a simple transformation or fallback, map and orElseGet can express the intent directly. If each branch does several things, an explicit branch that checks and unwraps the same local variable can be clearer. Calling get() on an empty instance throws NoSuchElementException.

Transforming with filter, map, and flatMap

filter keeps a value that meets a condition. For example, filter(name -> !name.trim().isEmpty()) drops blank names. map(String::trim) transforms the value, and a null mapping result becomes an empty Optional. If the next lookup already returns an Optional, use flatMap to avoid nesting. That lookup must return Optional.empty() when there is no result. A null result from the flatMap callback throws NullPointerException. With an empty input, none of the three callbacks runs, though all three methods require a non-null callback. Exceptions thrown by callbacks propagate to the caller, so Optional cannot prevent every NPE.

Running an action with ifPresent or ifPresentOrElse

Use ifPresent to display a name when available. Java 9’s ifPresentOrElse also accepts an action for an absent name. It uses only the callback for the selected branch. Logging or notifications are easier to spot in these methods or an explicit branch than inside map. When a long chain hides a business rule, give individual steps names with methods or local variables.

Falling back with or, orElse, and orElseGet

Java 9’s or takes a fallback that itself returns an Optional, such as a lookup in a secondary store. The supplier runs when the original is empty. A null supplier or a null result from it causes NullPointerException. orElse("Guest") suits a default value you already have. In orElse(guest("eager")), Java evaluates the argument before the call, so guest runs even when the buyer exists. In orElseGet(() -> guest("lazy")), the lambda body runs only when the value is absent. A factory call such as makeSupplier() in orElseGet(makeSupplier()) still follows ordinary argument evaluation. orElse(null) is allowed. Outside an explicit legacy boundary, it leaves the next caller responsible for handling null again.

Requiring a value with the two orElseThrow overloads

When the current operation treats absence as an error, Java 10’s orElseThrow() throws the same NoSuchElementException as get() and makes the failure path visible at the call site. Java 8’s orElseThrow(supplier) lets you create an exception that fits the operation. The supplier runs only when the value is absent. In that case a null supplier or result causes NullPointerException.

Flattening lookups with stream

Java 9’s stream() yields a sequential stream with one element or none. If a batch lookup gives you a Stream<Optional<T>>, flatMap(Optional::stream) keeps the available results in encounter order.

Object contracts for equals, hashCode, and toString

Two empty instances compare equal. When both hold values, equality follows the values’ equals method. The hash is the value’s hash or 0 when empty. Optional is a value-based class, so avoid using == to test for absence or equality and avoid locking on instances. toString() is for debugging and has no specified format. Keep it out of storage and parsing contracts.

Running the buyer lookup

After a lookup for ID 7 or 8, return the name if present, or call guest and return Guest if empty.

The diagram shows the two orElseGet paths in the example. ID 7 uses the name directly. Only ID 8 calls guest. The code also compares orElse and exercises the other methods below.

Save the following as OptionalDemo.java. The full example requires JDK 11 or later.

import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class OptionalDemo {
    static Optional<String> findBuyer(int id) {
        String name = id == 7 ? "Mina" : null;
        return Optional.ofNullable(name);
    }

    static String guest(String label) {
        System.out.println("fallback: " + label);
        return "Guest";
    }

    public static void main(String[] args) {
        Optional<String> buyer = findBuyer(7);
        Optional<String> missing = findBuyer(8);

        System.out.println("eager: " + buyer.orElse(guest("eager")));
        System.out.println("lazy: " +
                buyer.orElseGet(() -> guest("lazy")));
        System.out.println("missing: " +
                missing.orElseGet(() -> guest("missing")));

        System.out.println("map null is empty: " +
                buyer.map(name -> null).isEmpty());
        try {
            buyer.flatMap(name -> null);
        } catch (NullPointerException e) {
            System.out.println("flatMap: NullPointerException");
        }
        try {
            missing.get();
        } catch (NoSuchElementException e) {
            System.out.println("get: NoSuchElementException");
        }
        try {
            missing.orElseThrow();
        } catch (NoSuchElementException e) {
            System.out.println("orElseThrow: NoSuchElementException");
        }
        try {
            missing.orElseThrow(() -> new IllegalStateException("buyer 8"));
        } catch (IllegalStateException e) {
            System.out.println("custom: " + e.getMessage());
        }

        String names = Stream.of(buyer, missing)
                .flatMap(Optional::stream)
                .collect(Collectors.joining(", "));
        System.out.println("stream: " + names);
    }
}
javac -version
java -version
javac --release 11 OptionalDemo.java
java OptionalDemo

This is the output captured on Zulu OpenJDK 21.0.1. Separate API compilation probes used the same JDK’s javac --release to check the Java 8, 9, 10, and 11 availability boundaries. A small, separate example of the exception-supplier overload also compiled and ran on Java 8 itself.

fallback: eager
eager: Mina
lazy: Mina
fallback: missing
missing: Guest
map null is empty: true
flatMap: NullPointerException
get: NoSuchElementException
orElseThrow: NoSuchElementException
custom: buyer 8
stream: Mina

In the output, ID 7 triggers fallback: eager even though Mina exists. The orElseGet call for ID 7 prints lazy: Mina without calling guest. Only the orElseGet call for ID 8 prints fallback: missing and returns Guest.

Method reference

The number in parentheses is the Java release that introduced the method. For the factory methods, the last column describes the result or a null input.

Method Purpose and empty case
empty() (8) Return an empty result.
of(value) (8) Wrap a required value. NPE for null.
ofNullable(value) (8) Wrap a nullable value. Empty for null.
isPresent() (8) Test for presence. False when empty.
isEmpty() (11) Test for absence. True when empty.
get() (8) Unwrap the value. NoSuchElementException when empty.
filter(predicate) (8) Keep a matching value. Empty input stays empty.
map(mapper) (8) Transform the value. Empty for absent input or a null result.
flatMap(mapper) (8) Chain an Optional-returning lookup. Empty input stays empty.
ifPresent(action) (8) Run an action for a value. Do nothing when empty.
ifPresentOrElse(…) (9) Run one of two actions. Run the empty action when empty.
or(supplier) (9) Choose a fallback Optional. Call the supplier when empty.
orElse(value) (8) Choose a fallback value. Return the supplied argument when empty.
orElseGet(supplier) (8) Compute a fallback value. Call the supplier when empty.
orElseThrow() (10) Require a value. NoSuchElementException when empty.
orElseThrow(supplier) (8) Require a value. Throw the supplied exception when empty.
stream() (9) Get a sequential stream. No elements when empty.
equals(other) (8) Compare contents. An empty instance equals another empty Optional.
hashCode() (8) Hash the contents. Return 0 when empty.
toString() (8) Produce a debug string. Indicate absence when empty.

Choosing the return contract

If an order lookup succeeds and the buyer has no orders, an empty list is enough. Use Optional<List<T>> when an absent list and a retrieved list with zero elements mean different things. For example, return an empty Optional if there is no such buyer, and an Optional containing an empty list if the buyer exists and has no orders.

The JDK designed Optional primarily for return types. Fields and parameters can use it to express absence in the type, but they introduce wrapping at input boundaries and still allow a caller to pass a null reference. For DTOs and entities, check how your serializer or ORM reads and writes missing fields, explicit null, and values. If omitted fields and null mean different things in the API, use a model that preserves both states.

References

Discussion

View on GitHub ↗