Sub topic 9
Handling Missing Results with Optional
Some stream operations may have nothing to give back. If you ask for the first word that starts with "z" and no word does, the stream has no answer. Java handles this with Optional.
What Is Optional?
Optional is a small box that holds either one value or nothing. A box with a value is called "present." A box with nothing in it is called "empty."
Without Optional, a method might return null when it finds nothing. null is a special value that means "no object." If you forget to check for it, your program crashes with a NullPointerException. An Optional makes the chance of a missing result visible in the type itself, so you remember to handle it.
Which Operations Return Optional?
These terminal operations return an Optional because they might find nothing:
| Operation | What it looks for |
|---|---|
| `findFirst()` | The first element |
| `findAny()` | Any one element |
| `min(comparator)` | The smallest element |
| `max(comparator)` | The largest element |
A Worked Example
This program looks for words that start with "p" and then for words that start with "z."
import java.util.List;
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
List<String> words = List.of("kiwi", "plum", "pear");
Optional<String> firstP = words.stream()
.filter(w -> w.startsWith("p"))
.findFirst();
System.out.println(firstP.orElse("none")); // plum
String firstZ = words.stream()
.filter(w -> w.startsWith("z"))
.findFirst()
.orElse("none");
System.out.println(firstZ); // none
}
}The first search finds "plum," so orElse returns it. The second search finds nothing. Its Optional is empty, so orElse returns the default, "none."
Common Ways to Open the Box
orElse(default)returns the value, or the default if the box is empty.orElseGet(() -> ...)works the same way, but it only builds the default when the box is empty.ifPresent(value -> ...)runs code only when a value is present.isPresent()returnstrueif there is a value.orElseThrow()returns the value, or throws an exception if the box is empty.
import java.util.List;
public class IfPresentExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(3, 8, 5);
numbers.stream()
.filter(n -> n > 4)
.findFirst()
.ifPresent(n -> System.out.println("Found " + n)); // Found 8
}
}Exercise
Given List.of("red", "green", "blue"), write a pipeline that finds the first color longer than five letters and prints "unknown" if there is none. What does it print?
Show answer
System.out.println(List.of("red", "green", "blue").stream().filter(c -> c.length() > 5).findFirst().orElse("unknown")); prints "unknown", because "green" has exactly five letters and is not longer than five.
Exercise
Why does findFirst return an Optional instead of the element itself?
Show answer
The stream might be empty, or no element might match. An Optional shows that the result can be missing and makes you handle that case, instead of returning null.