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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
