Sub topic 9
Handling Missing Results with Optional
Some stream operations may not find anything. If you search a list for a word that starts with "z" and no word does, there is nothing to return. Java does not return null in that case. It gives you an Optional. This chapter shows what an Optional is, which stream operations return one, and how to get a value out of it safely.
What Optional Is
An Optional is a small box that holds either one value or nothing. A box that holds a value is called present. A box that holds nothing is called empty.
The type is written Optional<T>. Here T is the type of the value inside. For example, Optional<String> is a box that may hold a String.
Why not just use null? A null is a special value meaning "no object." If you forget to check for it and call a method on it, your program crashes with a NullPointerException. An Optional makes the possible absence visible in the type. When you see Optional<String>, you know right away that the result might be missing, and the compiler makes you unwrap the box before you can use the value.
Which Stream Operations Return Optional
A terminal operation is the last step of a pipeline. It produces the result. Some terminal operations always have an answer. count() returns 0 for an empty stream. collect returns an empty list. Other operations have no sensible answer for an empty stream, so they return an Optional.
| Operation | What it looks for | Return type |
|---|---|---|
| `findFirst()` | The first element | `Optional<T>` |
| `findAny()` | Any element | `Optional<T>` |
| `max(comparator)` | The largest element | `Optional<T>` |
| `min(comparator)` | The smallest element | `Optional<T>` |
| `reduce(function)` with no identity value | All elements combined | `Optional<T>` |
A First Example
This program searches a list twice. The first search finds a word. The second search finds nothing.
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 method orElse opens the box. If a value is present, orElse returns it. If the box is empty, orElse returns the default value you pass in, here "none".
The diagram below shows the decision that orElse makes.
Ways to Get the Value Out
There are several ways to open an Optional. Each one fits a different situation.
| Method | What it does when empty | Added in |
|---|---|---|
| `orElse(default)` | Returns the default | Java 8 |
| `orElseGet(supplier)` | Calls the supplier and returns its result | Java 8 |
| `orElseThrow(supplier)` | Throws the exception the supplier creates | Java 8 |
| `orElseThrow()` | Throws `NoSuchElementException` | Java 10 |
| `ifPresent(action)` | Does nothing | Java 8 |
| `ifPresentOrElse(action, emptyAction)` | Runs the empty action | Java 9 |
| `isPresent()` / `isEmpty()` | Returns `true` or `false` | Java 8 / Java 11 |
A supplier is a lambda that takes no input and returns a value, such as () -> "default".
Running Code Only When a Value Exists
Sometimes you do not need a default. You just want to act if something was found. Use ifPresent. You can also change the value inside the box with map. If the box is empty, map simply returns another empty box.
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
public class OptionalMethods {
public static void main(String[] args) {
List<String> words = List.of("kiwi", "plum", "banana");
Optional<String> longest = words.stream()
.max(Comparator.comparing(String::length));
longest.ifPresent(w -> System.out.println("Longest: " + w)); // Longest: banana
int length = longest.map(String::length).orElse(0);
System.out.println(length); // 6
Optional<String> blank = words.stream()
.filter(String::isEmpty)
.findFirst();
System.out.println(blank.isPresent()); // false
System.out.println(blank.map(String::length).orElse(0)); // 0
}
}Notice how map and orElse chain together. You never check for emptiness by hand.
Throwing an Error When Nothing Is Found
Sometimes a missing value means something went wrong. For example, a user ID that must exist is not in the list. In that case, throw an exception with a clear message.
import java.util.List;
public class OrElseThrowExample {
public static void main(String[] args) {
List<String> users = List.of("ana", "ben", "cleo");
try {
String user = users.stream()
.filter(u -> u.equals("dan"))
.findFirst()
.orElseThrow(() -> new IllegalStateException("User dan not found"));
System.out.println(user);
} catch (IllegalStateException e) {
System.out.println(e.getMessage()); // User dan not found
}
}
}orElse Versus orElseGet
These two look alike, but they behave differently. With orElse, Java computes the default value every time, even when the box holds a value. With orElseGet, Java runs the supplier only when the box is empty.
import java.util.Optional;
public class OrElseDemo {
static String expensiveDefault() {
System.out.println("computing default");
return "default";
}
public static void main(String[] args) {
Optional<String> found = Optional.of("plum");
String a = found.orElse(expensiveDefault());
// Prints: computing default
System.out.println(a); // plum
String b = found.orElseGet(OrElseDemo::expensiveDefault);
// Prints nothing extra
System.out.println(b); // plum
}
}Optional.of(value) creates a present box. Optional.empty() creates an empty one.
Common Mistakes
Calling get on an Empty Optional
Optional has a method called get(). It returns the value if present. On an empty box, it throws NoSuchElementException. That brings back the same crash you were trying to avoid with null.
Checking isPresent and Then Calling get
This code works, but it is clumsy:
import java.util.List;
import java.util.Optional;
public class ClumsyCheck {
public static void main(String[] args) {
Optional<String> first = List.of("kiwi", "plum").stream().findFirst();
if (first.isPresent()) {
System.out.println(first.get());
}
// Cleaner version of the same thing:
first.ifPresent(System.out::println);
}
}The one-line ifPresent version says the same thing with less room for error.
Expecting Optional to Hold null
findFirst throws a NullPointerException if the first element it finds is null. An Optional cannot hold null. If your list may contain null items, filter them out first with .filter(x -> x != null).
Optional for Primitive Streams
Streams of plain int, long, or double values use special box types: OptionalInt, OptionalLong, and OptionalDouble. These avoid wrapping each number in an object. A later chapter covers primitive streams in full. For now, note that the method to read the value is named getAsInt, getAsLong, or getAsDouble, and orElse works the same way.
import java.util.OptionalInt;
import java.util.stream.IntStream;
public class OptionalIntExample {
public static void main(String[] args) {
OptionalInt biggest = IntStream.of(3, 9, 4).max();
System.out.println(biggest.orElse(-1)); // 9
OptionalInt none = IntStream.empty().max();
System.out.println(none.orElse(-1)); // -1
}
}Summary
- An
Optionalis a box that is either present or empty. findFirst,findAny,max,min, andreducewithout an identity value return anOptional.- Use
orElsefor cheap defaults,orElseGetfor costly ones, andorElseThrowwhen absence is an error. - Use
ifPresentto act only when a value exists, andmapto change the value inside. - Avoid bare
get().
Exercise
Given List<Integer> nums = List.of(4, 8, 15), write one expression that finds the first number greater than 20 and returns -1 if there is none. What does it return?
Show answer
nums.stream().filter(n -> n > 20).findFirst().orElse(-1). No number is greater than 20, so findFirst returns an empty Optional and orElse returns -1.
Exercise
Why does found.orElse(loadDefault()) call loadDefault() even when found holds a value, and how do you fix it?
Show answer
Java evaluates the argument to orElse before calling the method, so loadDefault() always runs. Use found.orElseGet(() -> loadDefault()) instead. The supplier runs only when the Optional is empty.
Exercise
What is printed by Optional.of("pear").map(String::length).orElse(0), and what is printed if you start with Optional.empty() instead?
Show answer
The first prints 4, because map turns "pear" into its length. The second prints 0, because map on an empty Optional returns an empty Optional, and orElse supplies the default.