The Plain Picture#
A gift box that might be empty. You can check whether there's something inside, take it out, or say "if it's empty, give me this instead" — but you never get a nasty surprise from opening a box that wasn't there at all.
The Real Names#
Optional<T>is a container that holds either one value or nothing. It's designed as a return type for methods that might not find a result, making "no result" impossible to forget — unlike returningnull(Classes, Objects and Memory Ch 4).Create:
Optional.of(x)(x must not be null),Optional.ofNullable(x)(null → empty),Optional.empty().Stream methods like
findFirst,min,maxreturnOptional.
Under the Hood#
static Optional<Student> findByName(List<Student> all, String name) {
return all.stream().filter(s -> s.name().equals(name)).findFirst();
}
findByName(students, "Aisha").map(Student::score).orElse(0) // 200
findByName(students, "Zoya").map(Student::score).orElse(0) // 0 — no null anywhere
findByName(students, "Zoya").isPresent() // false
findByName(students, "Zoya").orElseThrow() // NoSuchElementException: No value presentThe methods: isPresent(), isEmpty(), ifPresent(consumer), map(f) (transform if present), flatMap(f) (when f itself returns an Optional),
filter(p), orElse(default), orElseGet(supplier), orElseThrow() / orElseThrow(() -> new NotFoundException(...)).
The orElse vs orElseGet trap#
static String expensive() {
System.out.println(" (expensive default computed)");
return "default";
}
Optional.of("real").orElse(expensive()); // prints "(expensive default computed)" — even though a value exists!
Optional.of("real").orElseGet(Modern::expensive); // prints nothingorElse(x) is a normal method call, so its argument is evaluated first, always. orElseGet(supplier) only calls the supplier if the Optional is empty.
Use orElse for constants, orElseGet for anything costly (a database call, building an object).
How to use Optional well#
✅ as a method return type when "no result" is normal:
Optional<User> findByEmail(String email).❌ not for fields, method parameters, or collections (return an empty list, not
Optional<List<...>>).❌ never call
.get()without checking — that's a NullPointerException with extra steps. Prefermap/orElse/orElseThrow.❌ never return
nullfrom a method whose return type isOptional.
Check yourself
4 questionsWhat problem does Optional solve?
Show answerHide answer
It makes "no result" explicit in the return type, so callers can't forget to handle it the way they forget null checks.
orElse vs orElseGet?
Show answerHide answer
orElse's argument is always evaluated; orElseGet only computes the default when the Optional is empty.
Where should you not use Optional?
Show answerHide answer
Fields, method parameters, and wrapping collections.
Rewrite without null checks: Student s = find(name); int score = (s == null) ? 0 : s.score();
Show answerHide answer
int score = find(name).map(Student::score).orElse(0); (with find returning Optional<Student>).