Optional
Optional is a container that holds one value or none, used as a return type to say "there may be no result" in a way the caller cannot overlook. This page explains what an Optional is and how its API grew from Java 8 to 11, then creates and unwraps Optionals, chains lookups through objects that may be missing, uses the Optionals that streams return, runs six traps, measures the cost, and lists where Optional does more harm than good.
Contents
What Optional is for
java.util.Optional<T>nullStringnullOptional<String>
Optional is a value-based class: instances that are equals==Serializable
| Method | Since | What it does | Best for |
|---|---|---|---|
ofofNullableempty | Java 8 | Create: ofofNullable | Wrapping a result in the method that returns it |
orElseorElseGetorElseThrow(supplier) | Java 8 | Unwrap with a default, a computed default or an exception | The end of a chain |
mapflatMapfilter | Java 8 | Transform or test the value only if present | Chaining lookups |
ifPresent | Java 8 | Run an action if present | Side effects |
ifPresentOrElseorstream | Java 9 | Both branches; a fallback Optional; zero or one element stream | Fallback lookups, flattening |
orElseThrow() | Java 10 | Like get() | When empty is a bug |
isEmpty | Java 11 | The opposite of isPresent | Readable conditions |
OptionalIntOptionalLongOptionalDoublemapflatMapfilter
Creating and unwrapping
A lookup in a small map of user emails returns an Optional. User 1 has an address, user 2 has a blank one, and user 9 does not exist, so every branch of the API gets used.
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
public class OptionalBasics {
static final Map<Integer, String> EMAILS = Map.of(1, "ada@example.com", 2, " ");
// Return Optional when "no result" is a normal outcome
static Optional<String> findEmail(int userId) {
return Optional.ofNullable(EMAILS.get(userId));
}
public static void main(String[] args) {
System.out.println("found: " + findEmail(1));
System.out.println("missing: " + findEmail(9));
// Getting the value out
System.out.println("orElse: " + findEmail(9).orElse("no email"));
System.out.println("orElseGet: " + findEmail(9).orElseGet(() -> "computed default"));
try {
findEmail(9).orElseThrow(() -> new IllegalArgumentException("user 9 has no email"));
} catch (IllegalArgumentException e) {
System.out.println("orElseThrow: " + e.getMessage());
}
findEmail(1).ifPresentOrElse(
e -> System.out.println("ifPresent: send to " + e),
() -> System.out.println("ifPresent: nothing to send"));
// Transforming without unwrapping
String domain = findEmail(1)
.map(e -> e.substring(e.indexOf('@') + 1))
.orElse("?");
System.out.println("map: " + domain);
System.out.println("filter blank: " + findEmail(2).filter(e -> !e.isBlank()).isPresent());
// Java 9 to 11 additions
System.out.println("or (Java 9): " + findEmail(9).or(() -> findEmail(1)).orElseThrow());
System.out.println("isEmpty (11): " + findEmail(9).isEmpty());
try {
findEmail(9).orElseThrow(); // Java 10: same as get()
} catch (NoSuchElementException e) {
System.out.println("orElseThrow(): NoSuchElementException: " + e.getMessage());
}
// Optional.of(null) fails immediately
try {
Optional.of(EMAILS.get(9));
} catch (NullPointerException e) {
System.out.println("Optional.of(null): NullPointerException");
}
}
}
Output:
found: Optional[ada@example.com]
missing: Optional.empty
orElse: no email
orElseGet: computed default
orElseThrow: user 9 has no email
ifPresent: send to ada@example.com
map: example.com
filter blank: false
or (Java 9): ada@example.com
isEmpty (11): true
orElseThrow(): NoSuchElementException: No value present
Optional.of(null): NullPointerException
turned the missing map entry intoofNullable ;Optional.empty threwof(null) at once. UseNullPointerException only when null would be a bug.of- The three ways out of an empty Optional gave a constant default, a computed default and an exception with a useful message.
with no argument (Java 10) throwsorElseThrow() with the message "No value present", which is whatNoSuchElementException does; the newer name makes the risk visible at the call site.get() extracted the domain without unwrapping, andmap turned the blank address into an empty Optional, so "user has a usable email" became one expression.filter (Java 9) tried a second lookup when the first was empty. Unlikeor , it keeps the result wrapped, so it can be chained further.orElse
Chaining lookups with map and flatMap
An order has a customer, who may have an address, which has a city. Order 1 has everything, order 2's customer has no address, and order 3 does not exist, which covers each place the chain can stop.
import java.util.List;
import java.util.Optional;
public class OptionalChains {
record Address(String city) {
}
// The field may be null; the accessor wraps it, so callers cannot forget the check
record Customer(String name, Address address) {
Optional<Address> findAddress() {
return Optional.ofNullable(address);
}
}
record Order(int id, Customer customer) {
}
static Optional<Order> findOrder(int id, List<Order> orders) {
return orders.stream().filter(o -> o.id() == id).findFirst();
}
static String expensiveDefault() {
System.out.println(" (expensiveDefault was called)");
return "unknown";
}
public static void main(String[] args) {
List<Order> orders = List.of(
new Order(1, new Customer("ann", new Address("Lyon"))),
new Order(2, new Customer("bob", null)));
for (int id : new int[] {1, 2, 3}) {
// flatMap: findAddress returns an Optional, so map would nest Optional<Optional<..>>
String city = findOrder(id, orders)
.map(Order::customer)
.flatMap(Customer::findAddress)
.map(Address::city)
.orElse("no city");
System.out.println("order " + id + ": " + city);
}
// orElse evaluates its argument even when a value is present; orElseGet does not
System.out.println("orElse with a value present:");
findOrder(1, orders).map(o -> o.customer().name()).orElse(expensiveDefault());
System.out.println("orElseGet with a value present:");
findOrder(1, orders).map(o -> o.customer().name())
.orElseGet(OptionalChains::expensiveDefault);
// Optional to stream: keep only present values
List<String> cities = orders.stream()
.map(o -> o.customer().findAddress())
.flatMap(Optional::stream)
.map(Address::city)
.toList();
System.out.println("known cities: " + cities);
}
}
Output:
order 1: Lyon
order 2: no city
order 3: no city
orElse with a value present:
(expensiveDefault was called)
orElseGet with a value present:
known cities: [Lyon]
- One chain replaced three nested null checks. Each step runs only if the previous one produced a value, and any missing link ends with "no city".
already returns anfindAddress , so the chain usesOptional . WithflatMap , the result would bemap . The rule is the same as for streams:Optional<Optional<Address>> for a plain function,map for a function that returns the wrapper type.flatMap calledorElse(expensiveDefault()) even though a value was present, because Java evaluates method arguments before the call.expensiveDefault takes a supplier and called it only when needed, which here was never. UseorElseGet for constants andorElse for anything that costs something or has side effects.orElseGet (Java 9) dropped the orders without an address and kept the city of the one that had one.flatMap(Optional::stream)
Optional in streams
Stream operations that may find nothing return an Optional, and primitive streams return the primitive variants. The program runs each kind on a short price list and on an empty one.
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class StreamOptionals {
record Item(String name, int price) { }
public static void main(String[] args) {
List<Item> items = List.of(new Item("pen", 2), new Item("book", 12), new Item("bag", 30));
List<Item> none = List.of();
// Terminal operations that may find nothing return Optional
Optional<Item> firstExpensive = items.stream().filter(i -> i.price() > 10).findFirst();
Optional<Item> cheapest = items.stream().min(Comparator.comparingInt(Item::price));
Optional<Integer> total = items.stream().map(Item::price).reduce(Integer::sum);
System.out.println("findFirst price > 10: " + firstExpensive.map(Item::name).orElse("-"));
System.out.println("min by price: " + cheapest.map(Item::name).orElse("-"));
System.out.println("reduce sum: " + total.orElse(0));
System.out.println("max of empty list: "
+ none.stream().max(Comparator.comparingInt(Item::price)));
// Primitive streams use OptionalInt, OptionalLong, OptionalDouble
OptionalInt maxPrice = items.stream().mapToInt(Item::price).max();
OptionalDouble avg = IntStream.empty().average();
System.out.println("max price: " + maxPrice.getAsInt());
System.out.println("average of nothing: " + avg + ", orElse " + avg.orElse(Double.NaN));
// Collectors.maxBy wraps the result per group
var byCheapness = items.stream().collect(Collectors.partitioningBy(i -> i.price() < 20,
Collectors.maxBy(Comparator.comparingInt(Item::price))));
System.out.println("most expensive under 20: " + byCheapness.get(true).map(Item::name)
.orElse("-"));
// Optional.stream (Java 9): flatten a list of Optionals
List<Optional<String>> lookups = List.of(Optional.of("a"), Optional.empty(),
Optional.of("c"));
System.out.println("present values: " + lookups.stream().flatMap(Optional::stream)
.toList());
}
}
Output:
findFirst price > 10: book
min by price: pen
reduce sum: 44
max of empty list: Optional.empty
max price: 30
average of nothing: OptionalDouble.empty, orElse NaN
most expensive under 20: book
present values: [a, c]
,findFirst ,min and the one-argumentmax returnreduce , because an empty stream has no first element, no minimum and no sum without an identity value. TheOptional of the empty list wasmax rather than an exception or a null.Optional.empty returned anIntStream.max , read withOptionalInt . The average of an empty stream isgetAsInt() , not 0 and notOptionalDouble.empty , so the program choseNaN explicitly.NaN insideCollectors.maxBy produced an Optional per group, because a group could be empty.partitioningBy- A list of Optionals is usually a sign that the code should have filtered earlier, but when you get one,
keeps the present values.flatMap(Optional::stream)
Six Optional traps
Optional removes the most common null bug, but it brings its own. Each trap below runs and prints what happens.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class OptionalTraps {
static Optional<String> badFind(String key) {
return null; // a method returning Optional... null
}
public static void main(String[] args) throws IOException {
// 1. map() turns a null result into an empty Optional, silently
Map<String, String> phones = new HashMap<>();
phones.put("ann", null);
Optional<String> phone = Optional.of("ann").map(phones::get);
System.out.println("1. map to a null result: " + phone);
// 2. get() on an empty Optional is no better than a null dereference
try {
Optional.empty().get();
} catch (RuntimeException e) {
System.out.println("2. get() on empty: " + e.getClass().getSimpleName()
+ ": " + e.getMessage());
}
// 3. An Optional reference can itself be null
try {
badFind("x").isPresent();
} catch (NullPointerException e) {
System.out.println("3. method returned null instead of Optional.empty(): NPE");
}
// 4. equals compares contents; == is unreliable on a value-based class
Optional<String> a = Optional.of("x");
Optional<String> b = Optional.of("x");
System.out.println("4. equals " + a.equals(b) + ", == " + (a == b)
+ ", empty() == empty() " + (Optional.empty() == Optional.empty()));
// 5. Optional is not Serializable, so it breaks serializable fields
try (ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream())) {
out.writeObject(Optional.of("x"));
} catch (NotSerializableException e) {
System.out.println("5. serializing: NotSerializableException " + e.getMessage());
}
// 6. orElse(null) brings the null straight back
String fallback = Optional.<String>empty().orElse(null);
System.out.println("6. orElse(null) gives " + fallback);
}
}
Output:
1. map to a null result: Optional.empty
2. get() on empty: NoSuchElementException: No value present
3. method returned null instead of Optional.empty(): NPE
4. equals true, == false, empty() == empty() true
5. serializing: NotSerializableException java.util.Optional
6. orElse(null) gives null
wraps its function's result withmap , so a function that returnsofNullable silently produces an empty Optional. Here "ann" exists but her phone entry is null, and the result looks the same as "no such person". If the difference matters, check it before mapping.null on an empty Optional throwsget() . CallingNoSuchElementException after anget() check is just a null check with more code; preferisPresent() ,orElse ormap .ifPresent- A method declared to return
returnedOptional , and the caller'snull threwisPresent() . Never return null from such a method; returnNullPointerException .Optional.empty() - Two Optionals of "x" are
but notequals , while the shared empty instance happens to be== to itself. Because Optional is value-based, identity comparisons are meaningless; always use== .equals - Writing an Optional with
threwObjectOutputStream . A serializable class with an Optional field cannot be serialized, which is one reason Optional fields are discouraged.NotSerializableException is allowed and returns plainorElse(null) . It is sometimes needed at the boundary with older APIs, but inside new code it throws away the point of the Optional.null
What Optional costs
An Optional is an object, so wrapping every result allocates. The program looks up 50 million names, a quarter of them missing, once with a plain null check and once with ofNullable(...).map(String::length).orElse(0)
import java.util.Optional;
public class OptionalCost {
static final String[] NAMES = new String[1024];
static {
for (int i = 0; i < NAMES.length; i++) {
NAMES[i] = i % 4 == 0 ? null : "name" + i; // a quarter are missing
}
}
static int withNullCheck(int i) {
String s = NAMES[i & 1023];
return s != null ? s.length() : 0;
}
static int withOptional(int i) {
return Optional.ofNullable(NAMES[i & 1023]).map(String::length).orElse(0);
}
public static void main(String[] args) {
int n = 50000000;
long bestNull = Long.MAX_VALUE;
long bestOpt = Long.MAX_VALUE;
long a = 0;
long b = 0;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
a = 0;
for (int i = 0; i < n; i++) {
a += withNullCheck(i);
}
bestNull = Math.min(bestNull, System.nanoTime() - t0);
t0 = System.nanoTime();
b = 0;
for (int i = 0; i < n; i++) {
b += withOptional(i);
}
bestOpt = Math.min(bestOpt, System.nanoTime() - t0);
}
System.out.println("same result: " + (a == b));
System.out.printf("null check: %,4d ms%n", bestNull / 1000000);
System.out.printf("Optional: %,4d ms%n", bestOpt / 1000000);
}
}
Output (2-CPU Linux machine, JDK 21, best of 3):
same result: true
null check: 32 ms
Optional: 273 ms
- Both versions computed the same total, and the Optional version was several times slower in this tight loop. Each call can allocate an
for the name and another for the mapped length, and the JIT's escape analysis does not always remove them.Optional - In absolute terms the cost is a few nanoseconds per call. For a method called once per request, or once per database row, it is irrelevant. For the inner loop of a numeric algorithm, a null check or a sentinel value is the better choice.
- As a field, an Optional adds an object of about 16 bytes per instance on a 64-bit JVM with compressed pointers, on top of the reference to it.
Where to use Optional, and where not
| Use | Recommendation |
|---|---|
| Return type of a lookup that may find nothing | Yes, this is its purpose |
| Return type of a method returning a collection | No: return an empty collection |
| Field of a class | No: use a nullable field, and an accessor that returns Optional if useful |
| Method or constructor parameter | No: overload the method, or accept null and document it |
| Element of a collection or value in a map | No: leave the element out instead |
| Hot numeric loops | No: use a null check, a sentinel, or OptionalInt |
| Ending a chain | orElseorElseGetorElseThrow |
| Bridging to code that expects null | orElse(null) |
Other tools also handle a missing value, and are often shorter. When you only need a default for a possibly null reference, Objects.requireNonNullElse(value, fallback)requireNonNullElseGetgetOrDefaultcomputeIfAbsentfindUsergetUser
Related pages: map