Optional in practice
Lesson 089 introduced the box. This one is about the four ways a program gets it wrong: a fallback that is computed for nothing, a field that adds a second kind of empty, a value unwrapped at the first line, and a collection of boxes where a filter belongs. Each has a program and a rule, and the rules are what the API documentation asks for.
orElse computes its argument
orElse(fallback) is a method call with an argument, and Java evaluates the argument before the call, so the fallback is computed whether or not the box is empty. The method below prints when it is called, which makes the order visible:
import java.util.Optional;
public class Eager {
public static void main(String[] args) {
Optional<String> present = Optional.of("value");
Optional<String> empty = Optional.empty();
System.out.println(present.orElse(fallback("orElse on present")));
System.out.println(present.orElseGet(() -> fallback("orElseGet on present")));
System.out.println(empty.orElse(fallback("orElse on empty")));
System.out.println(empty.orElseGet(() -> fallback("orElseGet on empty")));
}
static String fallback(String label) {
System.out.println("computing " + label);
return "fallback";
}
}
javac -Xlint:all Eager.java
java Eager
computing orElse on present
value
value
computing orElse on empty
fallback
computing orElseGet on empty
fallback
The first line is a computation whose result is thrown away, because the box had a value. The second call with a supplier printed nothing before value, and the two empty cases behave the same. The rule: a fallback that costs anything is a supplier, and orElse is for a constant.
A field of Optional
An Optional field reads like a promise and behaves like a second kind of empty: the field can be null and the box can be empty, so the code has two absences to handle. The program writes the same small class both ways:
import java.util.Optional;
public class Fields {
static class WithOptional {
private final Optional<String> nickname;
WithOptional(String nickname) {
this.nickname = Optional.ofNullable(nickname);
}
Optional<String> nickname() {
return nickname;
}
String display() {
return nickname.orElse("(none)");
}
}
static class WithNull {
private final String nickname;
WithNull(String nickname) {
this.nickname = nickname;
}
String display() {
return nickname == null ? "(none)" : nickname;
}
}
public static void main(String[] args) {
WithOptional a = new WithOptional("Ada");
WithOptional b = new WithOptional(null);
System.out.println(a.display() + " " + b.display());
System.out.println(b.nickname().isPresent());
WithNull c = new WithNull(null);
System.out.println(c.display());
}
}
javac -Xlint:all Fields.java
java Fields
Ada (none)
false
(none)
Both classes print the same text, and the one with the plain field is shorter and has one empty state instead of two. The optional field did not remove a null check; it moved it into the constructor and added a box per object. The documentation's rule is that Optional is for a return type, not for a field, a parameter or a collection element.
The throw nobody needs
orElseThrow() with no argument throws NoSuchElementException, like get, and a method that calls it on a value it just received has the exception of lesson 089 one line later. The program shows both that and the chain that does not need to unwrap at all:
import java.util.Optional;
public class Unwrapped {
public static void main(String[] args) {
Optional<String> empty = Optional.empty();
try {
String value = empty.orElseThrow();
System.out.println(value);
} catch (java.util.NoSuchElementException e) {
System.out.println("orElseThrow: " + e.getClass().getSimpleName());
}
String safe = empty.map(String::length).map(n -> "length " + n).orElse("no value");
System.out.println(safe);
}
}
javac -Xlint:all Unwrapped.java
java Unwrapped
orElseThrow: NoSuchElementException
no value
The second line is the shape that pays: the map steps run only when there is a value, and the single orElse at the end decides what a missing value means. A method that really must fail should use orElseThrow(() -> new IllegalStateException("...")) with a message of its own, which names the problem instead of the class of the box.
Optional in a collection
A List<Optional<String>> is a list whose elements may be missing, which is a list with holes. Most code does not want the holes: it wants the present values, and that is a filter. The program counts the wrapped values, builds the flat list with a loop, and then with flatMap(Optional::stream):
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class InList {
public static void main(String[] args) {
List<Optional<String>> wrapped = List.of(Optional.of("a"), Optional.empty(), Optional.of("b"));
int present = 0;
for (Optional<String> value : wrapped) {
if (value.isPresent()) {
present++;
}
}
System.out.println("wrapped: " + present + " of " + wrapped.size());
List<String> flat = new ArrayList<>();
for (Optional<String> value : wrapped) {
value.ifPresent(flat::add);
}
System.out.println(flat);
List<String> better = wrapped.stream().flatMap(Optional::stream).toList();
System.out.println(better);
}
}
javac -Xlint:all InList.java
java InList
wrapped: 2 of 3
[a, b]
[a, b]
The two flat lists are the same, and the last one is the shortest expression of "the values that are there". Optional::stream turns one box into a stream of zero or one elements, which is exactly the function flatMap of lesson 090 expects, and toList() collects them.
A list with holes is sometimes the honest model, for example a column of a table where a cell may be missing. When it is, the type List<Optional<T>> says so, and the filter above is one line. What is never right is a list of nulls and an Optional wrapper that is always present.
The rules of the API
Three rules cover the four programs. Use an Optional as the return type of a method that may find nothing, and nowhere else: not as a field, not as a parameter, not as an element unless the hole is the data. Prefer the methods that do not unwrap: map, filter, orElse, orElseGet, ifPresent. And when the value has to leave the box, choose the meaning of the absence once, with a constant, a supplier, or an exception whose message says what was missing.
The fourth mistake is the quiet one: a method that returns Optional and a caller that writes value.get() because the value is expected. Then the return type is a comment and the failure is a NoSuchElementException with no message at all, which is the worst diagnostic in the language.
Exercises
- Change the two orElseGet calls of Eager to orElse and count the computing lines.
- Give Fields a third class that stores the nickname in an array of one element and explain why it is worse than both.
- Turn the wrapped list of InList into a list of lengths, skipping the empty box.
- Write a method that returns an Optional and a caller that handles the absence with orElseThrow and a message.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why does
orElsecompute its argument even when the box has a value?Answer
The argument is evaluated before the method call, as in every Java call
Java evaluates arguments first, so a costly fallback belongs in orElseGet.
-
Why is an Optional field a regular mistake?
Answer
The field can be null as well, so there are two kinds of empty
A box adds an empty state without removing the null one, and the API asks for a return type.
-
What does
flatMap(Optional::stream)do to a list of boxes?Answer
Turns each box into zero or one element and joins the results
The stream of a present box has one element and the stream of an empty one has none.
-
What does this program print?
import java.util.Optional; public class Q1 { public static void main(String[] args) { System.out.println(Optional.of("a").map(String::length).orElse(0)); System.out.println(Optional.<String>empty().map(String::length).orElse(0)); } }Answer
1 / 0
The map turns the present string into its length, and the empty box keeps the default.
-
What does this program print?
import java.util.Optional; public class Q2 { public static void main(String[] args) { Optional<String> empty = Optional.empty(); System.out.println(empty.orElse("x") + empty.orElseGet(() -> "y")); } }Answer
xy
Both forms answer their fallback for an empty box, and the two are joined.
-
What does this program print?
import java.util.List; import java.util.Optional; public class Q3 { public static void main(String[] args) { List<Optional<Integer>> boxes = List.of(Optional.of(1), Optional.empty()); long count = boxes.stream().flatMap(Optional::stream).count(); System.out.println(count); } }Answer
1
Only the present box contributes an element to the flattened stream.
-
What does this program print?
import java.util.Optional; public class Q4 { public static void main(String[] args) { try { System.out.println(Optional.empty().orElseThrow()); } catch (RuntimeException e) { System.out.println("caught " + e.getClass().getSimpleName()); } } }Answer
caught NoSuchElementException
orElseThrow with no argument throws NoSuchElementException, which is a RuntimeException.
-
Why is
geta worse fit thanorElseThrowin a method that must fail?Answer
orElseThrow takes a supplier whose exception carries a message
The exception of get has no message, while orElseThrow lets the caller name the problem.
-
What are the two kinds of empty an Optional field introduces?
Answer
The field may be null and the box may be empty
A field is always nullable, so wrapping it adds an empty state instead of replacing one.
-
When is a
List<Optional<T>>the honest type?Answer
When the position matters and a value may be missing, as in a table column
The hole is the data there, so the type says so; otherwise a filter is what the caller wants.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev