Sub topic 10
Optional in Stream Pipelines
A stream is a sequence of items that you process step by step, such as filtering a list and then picking one item. Some stream steps cannot promise a result. If you ask for the first name that starts with "Z" and no name does, there is nothing to return. Java handles this case by returning an Optional.
This chapter shows which stream operations return Optional and how to use their results with the methods you already know.
Why Streams Return Optional
A terminal operation is the last step of a stream. It produces a final result and ends the stream. Some terminal operations always have an answer. For example, count() returns 0 for an empty stream. Other operations may have no answer at all:
- Finding the first item has no answer when no items are left.
- Finding the largest item has no answer when the stream is empty.
Before Optional, such methods might have returned null. The stream API returns an Optional instead, so the type itself tells you that the result might be missing.
| Operation | What it returns | Empty when |
|---|---|---|
| `findFirst()` | The first item | The stream has no items |
| `findAny()` | Any one item | The stream has no items |
| `max(comparator)` | The largest item | The stream has no items |
| `min(comparator)` | The smallest item | The stream has no items |
| `reduce(operator)` | All items combined into one | The stream has no items |
A comparator is an object that decides which of two items comes first. Comparator.comparing(String::length) compares strings by their length.
A Worked Example
This program uses each kind of operation and then reads the results safely.
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
public class StreamOptionalDemo {
public static void main(String[] args) {
List<String> names = List.of("Ana", "Bobby", "Ben");
Optional<String> firstB = names.stream()
.filter(n -> n.startsWith("B"))
.findFirst();
System.out.println(firstB.orElse("none")); // Bobby
Optional<String> firstZ = names.stream()
.filter(n -> n.startsWith("Z"))
.findFirst();
System.out.println(firstZ.orElse("none")); // none
Optional<String> longest = names.stream()
.max(Comparator.comparing(String::length));
System.out.println(longest.orElse("none")); // Bobby
Optional<String> joined = names.stream()
.reduce((a, b) -> a + "," + b);
System.out.println(joined.orElse("")); // Ana,Bobby,Ben
Optional<String> joinedEmpty = List.<String>of().stream()
.reduce((a, b) -> a + "," + b);
System.out.println(joinedEmpty.isPresent()); // false
}
}The code never checks for null. Each result is an Optional, and orElse supplies a fallback when the value is missing.
Keep Chaining After the Stream
The stream ends at the terminal operation, but the Optional it returns has its own methods. You can keep working with map, filter, and ifPresent:
import java.util.List;
public class ChainAfterStream {
public static void main(String[] args) {
List<String> names = List.of("Ana", "Bobby", "Ben");
String shout = names.stream()
.filter(n -> n.length() > 3)
.findFirst()
.map(String::toUpperCase)
.orElse("NO LONG NAME");
System.out.println(shout); // BOBBY
names.stream()
.filter(n -> n.startsWith("A"))
.findFirst()
.ifPresent(n -> System.out.println("Found " + n)); // Found Ana
}
}The first map call belongs to Optional, not to the stream. It changes the found value only if there is one.
Exercises
Exercise
What does this line print? System.out.println(List.of(4, 7, 10).stream().filter(n -> n > 20).findFirst().orElse(-1));
Show answer
It prints -1. No number is greater than 20, so findFirst returns an empty Optional, and orElse supplies -1.
Exercise
Why does max(comparator) return an Optional while count() returns a plain long?
Show answer
An empty stream still has a count, which is 0. An empty stream has no largest item, so max needs a way to say "no result". An empty Optional says that.
Exercise
Write a stream chain that finds the first name in List.of("Ana", "Bobby", "Ben") ending with "n", turns it to lower case, and prints "missing" if none is found.
Show answer
System.out.println(List.of("Ana", "Bobby", "Ben").stream().filter(n -> n.endsWith("n")).findFirst().map(String::toLowerCase).orElse("missing")); This prints ben.