Sub topic 10
Optional in Stream Pipelines
A stream is a sequence of values you can process step by step, such as filtering a list or sorting it. You get one by calling .stream() on a collection like a List. Some stream steps end with a single answer, for example "the first name that starts with B" or "the cheapest product." The list might be empty, or no item might match. In that case the stream has nothing to give you.
Java's answer for those cases is Optional. Several stream operations return an Optional instead of a plain value. This chapter shows which operations do that, why, and how to use their results with the tools you already know: orElse, ifPresent, map, and the rest.
Why Streams Return Optional
A terminal operation is the last step of a stream. It runs the pipeline and produces a result. Some terminal operations always have an answer. count() returns 0 for an empty stream, and collect(Collectors.toList()) returns an empty list.
Other terminal operations have no sensible answer for an empty stream. Take the "largest number in a list" as an example. If the list is empty, there is no largest number. Returning 0 would be a lie, since 0 might be a real value. Returning null would bring back all the problems from the first chapter.
So these operations return Optional. The return type itself says "there might be no answer here." The compiler then makes you deal with that case before you can use the value.
Stream Operations That Return Optional
These are the common operations you will meet:
| Operation | What it finds | Returns |
|---|---|---|
| `findFirst()` | The first element of the stream | `Optional<T>` |
| `findAny()` | Any one element (useful in parallel streams) | `Optional<T>` |
| `min(comparator)` | The smallest element by the given order | `Optional<T>` |
| `max(comparator)` | The largest element by the given order | `Optional<T>` |
| `reduce(accumulator)` | All elements combined into one | `Optional<T>` |
| `Collectors.minBy` / `Collectors.maxBy` | Smallest or largest, as a collector | `Optional<T>` |
| `IntStream.max()`, `average()`, and similar | Results from number streams | `OptionalInt`, `OptionalDouble`, and so on |
A comparator is an object that decides which of two values comes first. You usually build one with Comparator.comparing(...).
Finding an Element: findFirst and findAny
findFirst() returns the first element that reaches the end of the pipeline. It is usually placed after a filter, so it means "the first element that matches."
import java.util.List;
import java.util.Optional;
public class FindDemo {
public static void main(String[] args) {
List<String> names = List.of("Ana", "Bob", "Ben");
Optional<String> firstB = names.stream()
.filter(n -> n.startsWith("B"))
.findFirst();
System.out.println(firstB.orElse("none")); // Bob
Optional<String> firstZ = names.stream()
.filter(n -> n.startsWith("Z"))
.findFirst();
System.out.println(firstZ.orElse("none")); // none
System.out.println(firstZ.isPresent()); // false
}
}The first search finds "Bob", so the Optional holds it. The second search matches nothing, so the Optional is empty and orElse returns "none". No null appears anywhere, and nothing crashes.
findAny() works the same way, but it promises only "some matching element," not the first one. On a normal stream it usually gives the first element anyway. On a parallel stream, which splits work across several threads, findAny() can be faster because it does not have to wait to see which element came first. Use findFirst() when order matters and findAny() when any match will do.
Smallest and Largest: min and max
min and max take a comparator and return the smallest or largest element. They return an empty Optional when the stream is empty.
The example below uses a record, which is a short way to declare a class that just holds data. Records need Java 16 or later.
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
public class MinMaxDemo {
record Product(String name, double price) {}
public static void main(String[] args) {
List<Product> products = List.of(
new Product("Pen", 1.50),
new Product("Book", 12.00),
new Product("Bag", 30.00));
Optional<Product> cheapest = products.stream()
.min(Comparator.comparingDouble(Product::price));
cheapest.ifPresent(p -> System.out.println("Cheapest: " + p.name())); // Cheapest: Pen
String priciest = products.stream()
.max(Comparator.comparingDouble(Product::price))
.map(Product::name)
.orElse("no products");
System.out.println("Priciest: " + priciest); // Priciest: Bag
List<Product> none = List.of();
String result = none.stream()
.max(Comparator.comparingDouble(Product::price))
.map(Product::name)
.orElse("no products");
System.out.println(result); // no products
}
}Look at the second and third searches. After max returns an Optional, the code keeps chaining. map(Product::name) turns an Optional<Product> into an Optional<String>, and orElse gives the final text. You learned map in an earlier chapter, and it works the same way here. The same chain handles the empty list with no extra if checks.
Combining Everything: reduce
reduce combines all elements into one value, step by step. Summing numbers is the classic example. The one-argument form, reduce(accumulator), returns an Optional because an empty stream has nothing to combine.
import java.util.List;
import java.util.Optional;
public class ReduceDemo {
public static void main(String[] args) {
List<Integer> numbers = List.of(4, 7, 2);
Optional<Integer> sum = numbers.stream().reduce((a, b) -> a + b);
System.out.println(sum.orElse(0)); // 13
List<Integer> empty = List.of();
Optional<Integer> emptySum = empty.stream().reduce((a, b) -> a + b);
System.out.println(emptySum.isPresent()); // false
int withStart = empty.stream().reduce(0, (a, b) -> a + b);
System.out.println(withStart); // 0
}
}There is also a two-argument form, reduce(identity, accumulator). The identity is a starting value, such as 0 for addition. Because there is always a starting value, this form returns a plain value, not an Optional. Pick the form that fits your meaning:
- Use
reduce(0, ...)when an empty input has a natural answer, like a total of zero. - Use
reduce(...)without an identity when "no input" should be treated as "no answer."
A Quick Look at Number Streams
Streams of plain numbers, such as IntStream, have their own result types. IntStream.max() returns an OptionalInt rather than Optional<Integer>.
import java.util.OptionalInt;
import java.util.stream.IntStream;
public class NumberStreamDemo {
public static void main(String[] args) {
OptionalInt max = IntStream.of(3, 9, 4).max();
System.out.println(max.getAsInt()); // 9
OptionalInt emptyMax = IntStream.empty().max();
System.out.println(emptyMax.orElse(-1)); // -1
}
}The idea is the same: an empty stream gives an empty result. The next chapter covers OptionalInt, OptionalLong, and OptionalDouble in detail.
Edge Case: null Elements Inside the Stream
An Optional cannot hold null. This causes a surprise: if findFirst finds an element that is itself null, it throws a NullPointerException instead of returning an empty Optional. The same thing happens with findAny, min, max, and reduce when the chosen result is null.
List.of does not allow null, so this example uses Arrays.asList, which does.
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class NullElementDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList(null, "Bob");
try {
names.stream().findFirst();
} catch (NullPointerException e) {
System.out.println("findFirst cannot return a null element");
}
String first = names.stream()
.filter(Objects::nonNull)
.findFirst()
.orElse("none");
System.out.println(first); // Bob
}
}The fix is to remove null values before the terminal operation. filter(Objects::nonNull) does that in one step.
Common Mistakes
Here are mistakes beginners often make with Optional results from streams:
- Calling
get()right away. Writinglist.stream().findFirst().get()crashes withNoSuchElementExceptionwhen the list is empty. UseorElse,orElseGet, ororElseThrowinstead. - Checking with
isPresent()and then callingget(). This works, but it is the same as anif (x != null)check written the long way. A chain such as.map(...).orElse(...)is shorter and harder to get wrong. - Using
reducewithout an identity when zero is fine. If an empty total should be0, usereduce(0, ...)and skip the Optional entirely. Even simpler for numbers:mapToInt(Integer::intValue).sum(). - Expecting
findAnyto be predictable. On parallel streams it can return a different element each run. UsefindFirstif your result must be stable.
Worked Example: Finding the Oldest Adult
Let's put it together. We want the name of the oldest person who is at least 18, or a message if there is nobody.
import java.util.Comparator;
import java.util.List;
public class OldestAdult {
record Person(String name, int age) {}
static String oldestAdultName(List<Person> people) {
return people.stream()
.filter(p -> p.age() >= 18)
.max(Comparator.comparingInt(Person::age))
.map(Person::name)
.orElse("No adults found");
}
public static void main(String[] args) {
List<Person> group = List.of(
new Person("Mia", 15),
new Person("Tom", 42),
new Person("Zoe", 30));
System.out.println(oldestAdultName(group)); // Tom
List<Person> kids = List.of(new Person("Leo", 9));
System.out.println(oldestAdultName(kids)); // No adults found
}
}Step by step:
filterkeeps only people aged 18 or more.maxpicks the oldest of them and returnsOptional<Person>.map(Person::name)turns it intoOptional<String>.orElsegives the name, or the message if the Optional is empty.
The method never returns null, and it needs no if statements.
Exercise
What does this code print, and why? List<Integer> nums = List.of(); System.out.println(nums.stream().max(Integer::compare).orElse(-1));
Show answer
It prints -1. The list is empty, so max has no element to return and gives an empty Optional<Integer>. orElse(-1) then supplies the default value -1.
Exercise
Rewrite this line so it cannot throw an exception when no word is longer than 10 characters: String w = words.stream().filter(s -> s.length() > 10).findFirst().get();
Show answer
Replace get() with a safe retrieval method, for example: String w = words.stream().filter(s -> s.length() > 10).findFirst().orElse("none"); If a missing word is truly an error, use .orElseThrow(() -> new IllegalStateException("No long word")) to fail with a clear message.
Exercise
Why does Arrays.asList(null, "A").stream().findFirst() throw a NullPointerException instead of returning an empty Optional, and how do you avoid it?
Show answer
The first element is null, and an Optional cannot hold null, so findFirst throws. An empty Optional only means no element was found. Avoid it by adding .filter(Objects::nonNull) before findFirst so null elements are removed first.