Skip to lesson

Optional results from streams

A stream can be empty, and then some questions have no answer: there is no first element, no largest value, nothing to add up. Stream operations that may have no answer return an Optional, so the empty case is visible in the type.

Why some stream operations return Optional

When a stream is empty, some questions have no answer: a class with no students has no topper. Old code invented an answer: it returned null, or a fake value like -1 or Integer.MIN_VALUE.

NoTopper.javaJava
import java.util.*;
public class NoTopper {    public static void main(String[] args) {        List<Integer> none = List.of();        System.out.println(none.stream().max(Comparator.naturalOrder()));        List<Integer> marks = List.of(72, 88, 35);        System.out.println(marks.stream().max(Comparator.naturalOrder()));        System.out.println(marks.stream().filter(m -> m > 90).findFirst());    }}
Output
Optional.empty
Optional[88]
Optional.empty

A fake value is worse than null, because it looks real: an average of -1 marks can end up printed on a report.

Streams do not invent answers. findFirst(), findAny(), min(comparator), max(comparator) and reduce(operator) all return Optional<T>. A non-empty stream gives a present Optional; an empty one, including a stream where filter removed everything, gives Optional.empty.

findFirst, min, max and reduce

findFirst() gives the first element in the stream's order, min and max take a Comparator, and reduce(Integer::sum) combines all elements with an operator. Each returns an Optional, so you finish with the tools from earlier lessons: orElse, orElseThrow, map, ifPresentOrElse.

Example 1 · findFirst, min and max return Optional

FindMinMaxDemo.javaJava
import java.util.Comparator;import java.util.List;import java.util.Optional;
public class FindMinMaxDemo {    public static void main(String[] args) {        List<Integer> marks = List.of(67, 92, 45, 88, 92, 71);
        Optional<Integer> firstFail = marks.stream().filter(m -> m < 50).findFirst();        Optional<Integer> firstZero = marks.stream().filter(m -> m == 0).findFirst();        Optional<Integer> top = marks.stream().max(Comparator.naturalOrder());        Optional<Integer> lowest = marks.stream().min(Comparator.naturalOrder());
        System.out.println("first fail: " + firstFail);        System.out.println("first zero: " + firstZero);        System.out.println("top: " + top + ", lowest: " + lowest);
        List<Integer> emptyClass = List.of();        String topper = emptyClass.stream()                .max(Comparator.naturalOrder())                .map(m -> "Top score " + m)                .orElse("No marks yet");        System.out.println(topper);    }}
Output
first fail: Optional[45]
first zero: Optional.empty
top: Optional[92], lowest: Optional[45]
No marks yet

What this code does

  • filter can remove every element, so findFirst cannot promise a value: no mark is 0, and the result is Optional.empty.
  • An empty list gives an empty stream, and max returns Optional.empty instead of a fake value. map and orElse from earlier lessons finish the job.

Example 2 · reduce with and without a starting value

ReduceDemo.javaJava
import java.util.List;import java.util.Optional;
public class ReduceDemo {    public static void main(String[] args) {        List<Integer> fees = List.of(1200, 800, 1500);        List<Integer> none = List.of();
        Optional<Integer> total = fees.stream().reduce(Integer::sum);        Optional<Integer> emptyTotal = none.stream().reduce(Integer::sum);        System.out.println("reduce(op):    " + total + " / " + emptyTotal);
        int total2 = fees.stream().reduce(0, Integer::sum);        int emptyTotal2 = none.stream().reduce(0, Integer::sum);        System.out.println("reduce(0, op): " + total2 + " / " + emptyTotal2);
        Optional<Integer> biggest = none.stream().reduce(Integer::max);        System.out.println("biggest of none: " + biggest.map(String::valueOf).orElse("no fees"));    }}
Output
reduce(op):    Optional[3500] / Optional.empty
reduce(0, op): 3500 / 0
biggest of none: no fees

What this code does

  • reduce(Integer::sum) has no starting value, so for an empty stream it has nothing to return and gives Optional.empty.
  • reduce(0, Integer::sum) starts from 0, so an empty stream simply returns 0 and the result is a plain int. For "biggest" there is no honest starting value, so the Optional form is right.

reduce has a second form with a starting value, reduce(0, Integer::sum). The starting value, called the identity, is also the answer for an empty stream, so this form returns a plain value, not an Optional. Use it when a natural "nothing" answer exists, like 0 for a sum; use the Optional form when it does not, like the largest value.

OptionalInt and OptionalDouble from number streams

Number streams have their own Optional types that hold a primitive without boxing it. IntStream.max() and min() return OptionalInt; average() on any number stream returns OptionalDouble; LongStream has OptionalLong.

Example 3 · OptionalInt and OptionalDouble from IntStream

OptionalIntDemo.javaJava
import java.util.OptionalDouble;import java.util.OptionalInt;import java.util.stream.IntStream;
public class OptionalIntDemo {    public static void main(String[] args) {        int[] scores = {78, 92, 64, 80};        int[] noScores = {};
        OptionalInt best = IntStream.of(scores).max();        OptionalDouble avg = IntStream.of(scores).average();        OptionalDouble emptyAvg = IntStream.of(noScores).average();
        System.out.println(best + " " + avg + " " + emptyAvg);        System.out.println("best = " + best.getAsInt());        System.out.println("average = " + avg.orElse(0.0));        emptyAvg.ifPresentOrElse(                a -> System.out.println("average = " + a),                () -> System.out.println("no scores, no average"));
        int bestOdd = IntStream.of(scores).filter(s -> s % 2 == 1).max().orElse(-1);        System.out.println("best odd score, or -1: " + bestOdd);    }}
Output
OptionalInt[92] OptionalDouble[78.5] OptionalDouble.empty
best = 92
average = 78.5
no scores, no average
best odd score, or -1: -1

What this code does

  • max() on an IntStream returns OptionalInt, and average() returns OptionalDouble. They hold the primitive directly, with no Integer or Double object.
  • Read them with getAsInt(), orElse or ifPresentOrElse. All four scores are even, so the last max() is empty and orElse(-1) gives -1; here -1 is a deliberate choice of the caller, not a hidden fake value.

They are simpler than Optional. You read them with getAsInt() / getAsDouble() (which throw on empty, like get()), orElse, orElseGet, orElseThrow, isPresent, isEmpty, ifPresent and ifPresentOrElse. They have no map, filter or flatMap. If you need those, call boxed() on the stream first to get a Stream<Integer> and an Optional<Integer>.

Printing them shows the type: OptionalInt[92], OptionalDouble[78.5], OptionalDouble.empty.

Optional.stream (Java 9): drop the empty results

Mapping each roll number through findByRoll gives a Stream<Optional<Student>>: some boxes full, some empty. You usually want just the students that were found.

Example 4 · Optional.stream: keep only the students that were found

OptionalStreamDemo.javaJava
import java.util.List;import java.util.Optional;
record Student(int roll, String name) {}
public class OptionalStreamDemo {    static List<Student> students = List.of(            new Student(1, "Anil"), new Student(3, "Bhavya"), new Student(4, "Charu"));
    static Optional<Student> findByRoll(int roll) {        return students.stream().filter(s -> s.roll() == roll).findFirst();    }
    public static void main(String[] args) {        List<Integer> presentToday = List.of(4, 2, 1, 7);
        List<Optional<Student>> boxes = presentToday.stream().map(OptionalStreamDemo::findByRoll).toList();        System.out.println(boxes.size() + " boxes, first: " + boxes.get(0) + ", second: " + boxes.get(1));
        List<String> names = presentToday.stream()                .map(OptionalStreamDemo::findByRoll)                .flatMap(Optional::stream)                .map(Student::name)                .toList();        System.out.println("Java 9+: " + names);
        List<String> names8 = presentToday.stream()                .map(OptionalStreamDemo::findByRoll)                .filter(Optional::isPresent)                .map(Optional::get)                .map(Student::name)                .toList();        System.out.println("Java 8:  " + names8);    }}
Output
4 boxes, first: Optional[Student[roll=4, name=Charu]], second: Optional.empty
Java 9+: [Charu, Anil]
Java 8:  [Charu, Anil]

What this code does

  • Mapping roll numbers through findByRoll gives one Optional per roll; rolls 2 and 7 are not in the class, so their boxes are empty.
  • flatMap(Optional::stream) turns each full box into a one-element stream and each empty box into nothing, so only found students reach map(Student::name). The Java 8 form does the same with filter and get. (toList() on a stream is Java 16.)

Optional.stream(), added in Java 9, turns a present Optional into a stream of one element and an empty one into an empty stream. Combined with flatMap, it removes the empty boxes and unwraps the full ones in one step: .map(this::findByRoll).flatMap(Optional::stream). On Java 8 the same thing needs two steps: .filter(Optional::isPresent).map(Optional::get).

Real use: the latest order of each customer

A shop wants each customer's most recent order. For one customer it is filter by customer, then max by date, which returns an Optional because the customer may have no orders.

Example 5 · Real use: the latest order of each customer

LatestOrderDemo.javaJava
import java.time.LocalDate;import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.TreeMap;import java.util.stream.Collectors;
record Order(String customer, LocalDate date, int amount) {}
public class LatestOrderDemo {    public static void main(String[] args) {        List<Order> orders = List.of(                new Order("Ravi", LocalDate.of(2024, 3, 2), 450),                new Order("Sana", LocalDate.of(2024, 3, 5), 1200),                new Order("Ravi", LocalDate.of(2024, 3, 9), 300),                new Order("Sana", LocalDate.of(2024, 2, 28), 800),                new Order("Tara", LocalDate.of(2024, 3, 1), 150));        Comparator<Order> byDate = Comparator.comparing(Order::date);
        // One customer: may have no orders at all        for (String c : List.of("Ravi", "Uday")) {            Optional<Order> latest = orders.stream().filter(o -> o.customer().equals(c)).max(byDate);            System.out.println(c + ": " + latest.map(o -> o.date() + " Rs " + o.amount()).orElse("no orders"));        }
        // Every customer at once: groupingBy only makes groups that have orders        Map<String, Order> latestByCustomer = orders.stream()                .collect(Collectors.groupingBy(Order::customer, TreeMap::new,                        Collectors.collectingAndThen(Collectors.maxBy(byDate), Optional::orElseThrow)));        latestByCustomer.forEach((c, o) -> System.out.println(c + " -> " + o.date() + " Rs " + o.amount()));    }}
Output
Ravi: 2024-03-09 Rs 300
Uday: no orders
Ravi -> 2024-03-09 Rs 300
Sana -> 2024-03-05 Rs 1200
Tara -> 2024-03-01 Rs 150

What this code does

  • For one customer, filter then max(byDate) returns an Optional: Uday has no orders, so orElse("no orders") is used.
  • maxBy inside groupingBy also gives an Optional, but it can never be empty there, because a group exists only if it has an order. collectingAndThen(..., Optional::orElseThrow) unwraps it, and TreeMap::new keeps the customers in A to Z order.

For all customers at once, Collectors.groupingBy(Order::customer, Collectors.maxBy(byDate)) gives a Map<String, Optional<Order>>. Here the Optional is never empty, because groupingBy creates a group only when at least one order exists. Collectors.collectingAndThen(maxBy(byDate), Optional::orElseThrow) unwraps it, so the map holds plain Order values.

Next step

Check your understanding

12 quick questions