Optional: handling missing values
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- Final project: a library manager
The billion-dollar mistake in Java
Null is a value that means "nothing here". Calling a method on it throws NullPointerException, and every Java developer meets this exception hundreds of times. The deeper problem is that the type does not tell you whether a method may return null. You find out in production.
Java 8 added Optional<T>, a small container that holds either one value or nothing. When a method returns Optional<User>, the signature itself tells the caller: this may be empty, deal with it.
Creating and using an Optional
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
public class Main {
record Address(String city) {}
record User(String name, String email, Address address) {}
static final Map<Integer, User> USERS = Map.of(
1, new User("Ayesha", "ayesha@example.com", new Address("Lahore")),
2, new User("Bilal", null, null));
static Optional<User> findUser(int id) {
return Optional.ofNullable(USERS.get(id));
}
static Optional<String> email(User user) {
return Optional.ofNullable(user.email());
}
static Optional<Address> address(User user) {
return Optional.ofNullable(user.address());
}
public static void main(String[] args) {
// Three ways to create one
Optional<String> empty = Optional.empty();
Optional<String> present = Optional.of("value"); // throws if the argument is null
Optional<String> maybe = Optional.ofNullable(null); // empty if null
System.out.println(empty + " " + present + " " + maybe);
// Reading the value safely
System.out.println(findUser(1).map(User::name).orElse("unknown"));
System.out.println(findUser(99).map(User::name).orElse("unknown"));
// orElse always evaluates its argument; orElseGet only when needed
String lazy = findUser(1).map(User::name).orElseGet(() -> expensiveDefault());
System.out.println(lazy);
// orElseThrow for "must exist"
try {
findUser(99).orElseThrow(() -> new NoSuchElementException("User 99 not found"));
} catch (NoSuchElementException e) {
System.out.println(e.getMessage());
}
// ifPresent and ifPresentOrElse
findUser(2).ifPresent(u -> System.out.println("Found " + u.name()));
findUser(2).flatMap(Main::email).ifPresentOrElse(
e -> System.out.println("Email: " + e),
() -> System.out.println("Bilal has no email"));
// Chaining with flatMap avoids nested null checks
String city = findUser(1)
.flatMap(Main::address)
.map(Address::city)
.orElse("no address");
System.out.println(city);
String city2 = findUser(2)
.flatMap(Main::address)
.map(Address::city)
.orElse("no address");
System.out.println(city2);
// filter keeps the value only if the predicate is true
Optional<String> longEmail = findUser(1).flatMap(Main::email).filter(e -> e.length() > 30);
System.out.println(longEmail.isPresent());
// Streams of Optionals
long withEmail = List.of(1, 2, 99).stream()
.map(Main::findUser)
.flatMap(Optional::stream)
.filter(u -> u.email() != null)
.count();
System.out.println("Users with email: " + withEmail);
}
static String expensiveDefault() {
System.out.println("(computing a default)");
return "default";
}
}
Walking through it
There are three factory methods. Optional.empty() is an empty one. Optional.of(x) wraps a value and throws NullPointerException if x is null, which is useful when null would be a bug. Optional.ofNullable(x) turns null into empty, and it is the one you use when wrapping values that come from old code. findUser does exactly that with a map lookup.
The main idea is to avoid get(). The method get() throws NoSuchElementException when empty, so calling it without a check just moves the null problem. Use one of the safer ways to unwrap.
orElse(x)gives a fixed fallback.orElseGet(supplier)computes the fallback only when needed. In the example, the "(computing a default)" line never prints, because the user exists. WithorElse(expensiveDefault()), it would be computed every time, even when unused. UseorElseGetwhen the default costs something.orElseThrow(supplier)is the right choice when absence is an error. Since Java 10, there is also a no-argumentorElseThrow().ifPresentandifPresentOrElserun code for the present or empty case.
The chain with map and flatMap is where Optional pays off. map transforms the value if there is one, and the result is wrapped again. flatMap is for functions that already return an Optional, so you do not end up with Optional<Optional<...>>. Look at the city lookup. Without Optional, it would need a null check for the user, one for the address and one for the city. With it, the same logic is one readable pipeline, and a missing link anywhere gives the fallback "no address".
filter turns a present value into empty if the predicate fails. Optional.stream(), added in Java 9, turns an Optional into a stream of zero or one elements, which is neat for dropping the empty ones with flatMap.
Where Optional does not belong
- Fields. Optional is not serialisable and adds an extra object. Keep a nullable field, or model the absence in another way.
- Method parameters. Callers then have to wrap values. Use overloads, or accept null with a clear contract.
- Collections. Return an empty list instead of
Optional<List<T>>. - Everywhere else. It is designed mainly as a return type for methods that may have no result.
Also, never return null from a method that returns Optional. It defeats the whole idea.
Common mistakes
- Calling
get()withoutisPresent(). And thenif (opt.isPresent()) opt.get()is just a clumsy null check. Prefermap,orElseand friends. - Using
orElsewith an expensive call. UseorElseGet. - Using
Optional.ofon a value that may be null. - Using Optional for fields and parameters.
- Using
mapwhereflatMapis needed, and getting a nested Optional.
Try it yourself
- Write
Optional<Integer> parse(String text)that returns empty for non-numbers instead of throwing. - Write a method that returns the longest word in a list as an Optional, empty for an empty list.
- Extend the example with a
Companyrecord and a user-to-company-to-country chain usingflatMap.
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
public class Main {
record Address(String city) {}
record User(String name, String email, Address address) {}
static final Map<Integer, User> USERS = Map.of(
1, new User("Ayesha", "ayesha@example.com", new Address("Lahore")),
2, new User("Bilal", null, null));
static Optional<User> findUser(int id) {
return Optional.ofNullable(USERS.get(id));
}
static Optional<String> email(User user) {
return Optional.ofNullable(user.email());
}
static Optional<Address> address(User user) {
return Optional.ofNullable(user.address());
}
public static void main(String[] args) {
// Three ways to create one
Optional<String> empty = Optional.empty();
Optional<String> present = Optional.of("value"); // throws if the argument is null
Optional<String> maybe = Optional.ofNullable(null); // empty if null
System.out.println(empty + " " + present + " " + maybe);
// Reading the value safely
System.out.println(findUser(1).map(User::name).orElse("unknown"));
System.out.println(findUser(99).map(User::name).orElse("unknown"));
// orElse always evaluates its argument; orElseGet only when needed
String lazy = findUser(1).map(User::name).orElseGet(() -> expensiveDefault());
System.out.println(lazy);
// orElseThrow for "must exist"
try {
findUser(99).orElseThrow(() -> new NoSuchElementException("User 99 not found"));
} catch (NoSuchElementException e) {
System.out.println(e.getMessage());
}
// ifPresent and ifPresentOrElse
findUser(2).ifPresent(u -> System.out.println("Found " + u.name()));
findUser(2).flatMap(Main::email).ifPresentOrElse(
e -> System.out.println("Email: " + e),
() -> System.out.println("Bilal has no email"));
// Chaining with flatMap avoids nested null checks
String city = findUser(1)
.flatMap(Main::address)
.map(Address::city)
.orElse("no address");
System.out.println(city);
String city2 = findUser(2)
.flatMap(Main::address)
.map(Address::city)
.orElse("no address");
System.out.println(city2);
// filter keeps the value only if the predicate is true
Optional<String> longEmail = findUser(1).flatMap(Main::email).filter(e -> e.length() > 30);
System.out.println(longEmail.isPresent());
// Streams of Optionals
long withEmail = List.of(1, 2, 99).stream()
.map(Main::findUser)
.flatMap(Optional::stream)
.filter(u -> u.email() != null)
.count();
System.out.println("Users with email: " + withEmail);
}
static String expensiveDefault() {
System.out.println("(computing a default)");
return "default";
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account