Java / Java 21 Interview Questions
How has Optional been improved and how should it be used correctly?
Optional<T> (Java 8) is a container for a value that may or may not be present. It is designed to be a return type that makes the absence of a value explicit in the API contract, not a replacement for null in all contexts.
| Method | Since | Purpose |
|---|---|---|
| of(T) / ofNullable(T) / empty() | 8 | Factory methods |
| isPresent() / isEmpty() | 8 / 11 | isEmpty() added Java 11 |
| get() / orElse(T) / orElseGet(Supplier) | 8 | Extract value (orElseGet lazier) |
| orElseThrow(Supplier) | 8 | Throw custom exception if empty |
| map() / flatMap() / filter() | 8 | Transform the value |
| ifPresent(Consumer) / ifPresentOrElse() | 8 / 9 | ifPresentOrElse added Java 9 |
| or(Supplier<Optional>) | 9 | Return this if present, else the supplied Optional |
| stream() | 9 | Returns Stream of 0 or 1 elements |
// Correct use — as a return type
Optional findById(long id) {
return Optional.ofNullable(repository.get(id));
}
// Chaining without get()
findById(42)
.filter(u -> u.isActive())
.map(User::email)
.ifPresent(email -> sendNotification(email));
// or() — Java 9: fallback to another Optional
Optional user = findById(42)
.or(() -> findByEmail("alice@example.com"));
// ifPresentOrElse — Java 9
findById(42).ifPresentOrElse(
user -> System.out.println("Found: " + user),
() -> System.out.println("Not found")
);
// stream() — Java 9: use Optional in flatMap on a stream of Optionals
List> opts = List.of(Optional.of("a"), Optional.empty(), Optional.of("b"));
List present = opts.stream()
.flatMap(Optional::stream) // ["a", "b"]
.toList();
// ANTI-PATTERNS:
// opt.isPresent() ? opt.get() : default -- use orElse(default)
// Optional> -- use flatMap
// Optional as a field -- use null or an explicit state enum
// Optional as a parameter -- use method overloading
More Related questions...