00:00

Optional with the Java Stream API

Last updated:

java.util.Optional<T>, added in Java 8, is a container that holds either one non-null value or nothing. The Stream API returns an Optional from every terminal operation whose result might not exist: findFirst(), findAny(), min(), max() and the one-argument reduce(). Primitive streams return OptionalInt, OptionalLong and OptionalDouble.

This tutorial shows how to consume those results well: transform them with map() and filter(), supply defaults, throw meaningful exceptions, and use the methods added in Java 9, 10 and 11, without ever calling get() blindly.

1. Syntax and Key Methods

Optional.java (API)
// Stream methods that return Optional (Java 8)
Optional<T> findFirst()          Optional<T> findAny()
Optional<T> min(Comparator<? super T> c)    Optional<T> max(Comparator<? super T> c)
Optional<T> reduce(BinaryOperator<T> accumulator)

// Commonly used java.util.Optional<T> methods
<U> Optional<U> map(Function<? super T, ? extends U> f)            // Java 8
<U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> f)
Optional<T> filter(Predicate<? super T> p)
T orElse(T other)    T orElseGet(Supplier<? extends T> s)
T orElseThrow()                                                    // Java 10
<X extends Throwable> T orElseThrow(Supplier<? extends X> s)       // Java 8
void ifPresentOrElse(Consumer<? super T> a, Runnable empty)        // Java 9
Optional<T> or(Supplier<? extends Optional<? extends T>> s)        // Java 9
boolean isEmpty()                                                  // Java 11

2. How Optional Works with Streams

An Optional is either present (holds a value) or empty. Its map(), flatMap() and filter() apply their function only when a value is present and return an empty Optional otherwise. That lets you chain transformations on a stream's result exactly like stream steps, and decide what "nothing" means only at the end.

The terminal methods choose that meaning: orElse() returns a default value, orElseGet() computes one lazily, orElseThrow() signals an error, and ifPresent() or ifPresentOrElse() run an action.

A stream result flowing through Optional methods A list of customers is filtered by city and findFirst returns an Optional of Customer. map extracts the email, filter keeps it only if verified, and orElse supplies a fallback address when any step produced an empty Optional. customers.stream() STREAM findFirst()Optional<Cust> map(email)Optional email filterverified? orElse(...)a String VALUE OPTIONAL CHAIN
Figure 1: Each Optional method passes an empty result straight through, so the chain needs no null checks; the default is applied once, at the end.

3. Java Examples

Example 1: Transforming a found element (Java 16+)

Find the first verified email of a customer in a city, with a fallback support address.

FirstVerifiedEmail.java
import java.util.List;

public class FirstVerifiedEmail {

    record Customer(String name, String city, String email, boolean verified) { }

    static String contactFor(List<Customer> customers, String city) {
        return customers.stream()
                .filter(c -> c.city().equals(city))
                .findFirst()
                .filter(Customer::verified)
                .map(Customer::email)
                .orElse("support@shop.example");
    }

    public static void main(String[] args) {
        List<Customer> customers = List.of(
                new Customer("Ana", "Pune", "ana@mail.in", true),
                new Customer("Raj", "Delhi", "raj@mail.in", false));

        System.out.println("Pune:   " + contactFor(customers, "Pune"));
        System.out.println("Delhi:  " + contactFor(customers, "Delhi"));
        System.out.println("Chennai: " + contactFor(customers, "Chennai"));
    }
}
Output
Pune:   ana@mail.in
Delhi:  support@shop.example
Chennai: support@shop.example

How it works: Delhi's customer is not verified, so Optional.filter() empties the result; Chennai has no customer at all. Both cases fall through to the same orElse() without any if statements.

Example 2: orElse() compared with orElseGet() (Java 9+)

Look up a cached price and fall back to an expensive calculation only when needed.

OrElseVsOrElseGet.java
import java.util.List;
import java.util.Optional;

public class OrElseVsOrElseGet {

    static int expensivePriceLookup() {
        System.out.println("  (expensive lookup ran)");
        return 999;
    }

    public static void main(String[] args) {
        List<Integer> cachedPrices = List.of(450, 520);

        System.out.println("orElse:");
        int a = cachedPrices.stream().findFirst().orElse(expensivePriceLookup());
        System.out.println("  price " + a);

        System.out.println("orElseGet:");
        int b = cachedPrices.stream().findFirst().orElseGet(OrElseVsOrElseGet::expensivePriceLookup);
        System.out.println("  price " + b);
    }
}
Output
orElse:
  (expensive lookup ran)
  price 450
orElseGet:
  price 450

How it works: The argument of orElse() is always evaluated, even when a value is present. orElseGet() takes a Supplier and calls it only when the Optional is empty, so it is the right choice for costly defaults.

Example 3: Throwing a meaningful exception (Java 16+)

An order service must fail clearly when an order id does not exist.

OrderLookup.java
import java.util.List;
import java.util.NoSuchElementException;

public class OrderLookup {

    record Order(String id, int total) { }

    static class OrderNotFoundException extends RuntimeException {
        OrderNotFoundException(String id) { super("Order not found: " + id); }
    }

    static final List<Order> ORDERS = List.of(new Order("A-1", 1200), new Order("A-2", 640));

    static Order find(String id) {
        return ORDERS.stream()
                .filter(o -> o.id().equals(id))
                .findFirst()
                .orElseThrow(() -> new OrderNotFoundException(id));
    }

    public static void main(String[] args) {
        System.out.println("A-2 total: " + find("A-2").total());
        try {
            find("Z-9");
        } catch (OrderNotFoundException e) {
            System.out.println(e.getMessage());
        }
        try {
            ORDERS.stream().filter(o -> o.total() > 5000).findFirst().orElseThrow();
        } catch (NoSuchElementException e) {
            System.out.println("orElseThrow(): " + e.getMessage());
        }
    }
}
Output
A-2 total: 640
Order not found: Z-9
orElseThrow(): No value present

How it works: orElseThrow(supplier) throws your own exception with a useful message. The no-argument orElseThrow() (Java 10) throws NoSuchElementException and is the readable replacement for get().

Example 4: Java 9 and primitive optionals (Java 9+)

Report the highest bid, or say there were no bids, and fall back to a secondary source of offers.

ModernOptionalMethods.java
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.IntStream;

public class ModernOptionalMethods {

    public static void main(String[] args) {
        OptionalInt highest = IntStream.of(4200, 5100, 4800).max();
        highest.ifPresentOrElse(
                bid -> System.out.println("Highest bid: " + bid),
                () -> System.out.println("No bids"));

        OptionalInt none = IntStream.empty().max();
        none.ifPresentOrElse(
                bid -> System.out.println("Highest bid: " + bid),
                () -> System.out.println("No bids"));

        List<String> primary = List.of();
        List<String> backup = List.of("OFFER-7");
        String offer = primary.stream().findFirst()
                .or(() -> backup.stream().findFirst())
                .orElse("none");
        System.out.println("Offer: " + offer);
    }
}
Output
Highest bid: 5100
No bids
Offer: OFFER-7

How it works: ifPresentOrElse() (Java 9) handles both cases in one call. or() (Java 9) supplies another Optional lazily, which is handy for chains of fallbacks. OptionalInt has no map(); use getAsInt(), orElse() or ifPresent().

4. Real-World Use Cases

  • Repository-style lookups: findFirst() plus orElseThrow() for "not found" errors.
  • Optional configuration: chain fallbacks with or(): user setting, then team setting, then default.
  • Display values: map(...).orElse("-") for UI fields that may be missing.
  • Extremes: max() results with ifPresentOrElse() for "no data" messages.

5. Important Points

  • Never call get() without knowing a value is present; prefer orElseThrow().
  • orElse() always evaluates its argument; use orElseGet() for costly defaults.
  • Optional cannot hold null: findFirst() throws NullPointerException if the first element is null.
  • Return type, not field type: Optional is designed for method return values, not for fields or parameters.
  • Primitive optionals have fewer methods (no map() or filter()).

6. Ways to Handle an Empty Optional

MethodWhen the Optional is emptySince
orElse(value)Returns the value (always evaluated)8
orElseGet(supplier)Calls the supplier8
orElseThrow(supplier)Throws your exception8
orElseThrow()Throws NoSuchElementException10
or(supplier)Returns another Optional9
ifPresentOrElse(a, r)Runs the Runnable9
stream()Returns an empty stream9

Optional.stream() connects optionals back to streams; see Optional.stream().

7. Common Mistakes and Best Practices

Calling get() blindly

Wrong
String email = customers.stream().filter(c -> c.vip()).findFirst().get().email();   // NoSuchElementException if no VIP

Use map(Customer::email).orElse(...) or orElseThrow() with a clear message.

Checking isPresent() and then calling get()

Verbose
Optional<Order> o = orders.stream().findFirst();
if (o.isPresent()) { process(o.get()); }        // works, but verbose
Better
orders.stream().findFirst().ifPresent(this::process);

Other mistakes to avoid

  • Returning null from a method declared to return Optional. Return Optional.empty().
  • Using orElse(expensiveCall()). Use orElseGet().
  • Wrapping collections in Optional. Return an empty collection instead.

8. Summary

  • Streams return Optional from operations whose result may not exist.
  • Chain map(), filter() and flatMap(), then resolve the empty case once at the end.
  • Prefer orElseGet() for costly defaults and orElseThrow() over get().
  • Java 9+ adds or(), ifPresentOrElse() and stream().

9. References