Java Optional Best Practices: Pitfalls, Creating Optionals, flatMap and stream()
How not to use Java Optional (get, isPresent, Optional fields and parameters), how to create Optionals with of, ofNullable and empty, how to chain Optional-returning methods with flatMap, and how Optional.stream drops missing values in a stream pipeline.
kvi5hnuCode Sprout team member9 min readOn this page
The previous article showed the three good ways to work with an Optional: supply a fallback, consume the value if present, or transform it inside the Optional. This article completes the picture. First come the habits that make Optional pointless. Then you'll see how to create Optionals in your own methods, how to chain several Optional-returning methods with flatMap, and how to turn Optionals into streams so that missing values simply disappear from a pipeline.
How not to work with Optional
get() returns the wrapped value, or throws NoSuchElementException if there isn't one. So
optionalValue.get().someMethod()
is no safer than calling value.someMethod() on a reference that might be null. You've only renamed the exception. Likewise, isPresent() and isEmpty() (Java 11) tell you whether there's a value, but
if (optionalValue.isPresent()) optionalValue.get().someMethod();
is no easier than if (value != null) value.someMethod();. If you find yourself calling get, isPresent or isEmpty, look for a way to use map, filter, ifPresent or one of the orElse methods instead. Usually there is one, and the result is shorter.
Rules of thumb for Optional
These guidelines come from the people who designed the API, and most code style guides adopt them:
- A variable of type
Optionalshould never benull. An Optional that is itselfnullcombines the disadvantages of both approaches. ReturnOptional.empty(), nevernull, from a method declared to return anOptional. - Use
Optionalmainly as a return type. It was designed to say "this method may have no result". That's its sweet spot. - Don't use fields of type
Optional. It costs an extra object per field, and inside a class, anullfield that is checked in one place is perfectly manageable.Optionaldeliberately does not implementSerializable, which also discourages Optional fields. You can still offer an accessor such asOptional<String> getMiddleName()that wraps a nullable field. - Be wary of
Optionalparameters. They make calls clumsy in the common case: callers must writeprocess(Optional.of(x))instead ofprocess(x). Consider two overloads, one with the parameter and one without. - Don't put Optionals in collections or use them as map keys. A
List<Optional<String>>is a list of maybe-strings. Collect the values that are present instead, as shown at the end of this article. - Don't compare Optionals with
==or synchronize on them.Optionalis a value-based class: two Optionals with equal contents may or may not be the same object. Useequals, which compares the wrapped values. - Prefer
OptionalInt,OptionalLongandOptionalDoublefor primitives. Primitive streams return them (article 16), and they avoid boxing.
Creating Optional values
When you write a method that may have no result, return one of these:
Optional.of(value) // a present value; throws NullPointerException if value is null
Optional.empty() // no value
Optional.ofNullable(value) // of(value) if value != null, empty() otherwise
For example, a "safe" inverse that has no answer for zero:
public static Optional<Double> inverse(Double x) {
return x == 0 ? Optional.empty() : Optional.of(1 / x);
}
ofNullable is the bridge from the old "object or null" world. Wrap the result of a method that may return null, such as Map.get or System.getProperty, and continue with Optional methods. Use of when the value can't be null. If it unexpectedly is, failing fast with an exception right there is better than carrying an empty Optional around.
Composing Optional functions with flatMap
Suppose you have a method f that returns an Optional<T>, and T has a method g that returns an Optional<U>. With plain methods, you'd write s.f().g(). That doesn't compile here, because s.f() is an Optional<T>, not a T. And map doesn't help: s.f().map(T::g) gives an Optional<Optional<U>>. Use flatMap, which applies the function and flattens the result:
Optional<U> result = s.f().flatMap(T::g);
If s.f() is empty, g isn't called and the result is empty. Otherwise, the result is whatever g returns.
With a safe square root alongside the safe inverse
public static Optional<Double> squareRoot(Double x) {
return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
}
you can compute the square root of the inverse:
Optional<Double> result = inverse(x).flatMap(MyMath::squareRoot);
Starting from Optional.of(x) makes a longer chain look uniform:
Optional<Double> result = Optional.of(x)
.flatMap(MyMath::inverse)
.flatMap(MyMath::squareRoot);
The chain succeeds only if every step does. If any step returns an empty Optional, the remaining steps are skipped and the result is empty. Use this::inverse for instance methods and ClassName::inverse for static ones.
This is the same idea as Stream.flatMap from article 3. Think of an Optional as a stream of zero or one elements again: mapping an Optional-returning function gives an Optional of an Optional, and flatMap flattens it.
| You have | The function returns | Use |
|---|---|---|
Optional<T> | U (or null for "nothing") | map |
Optional<T> | Optional<U> | flatMap |
Stream<T> | Stream<U> | flatMap |
Stream<T> | Optional<U> | map(...).flatMap(Optional::stream) |
Turning an Optional into a stream
Optional.stream() (Java 9) returns a stream with zero or one element. That sounds useless until you have a stream of IDs and a lookup method that returns an Optional:
Optional<User> lookup(String id)
How do you get a stream of the users that exist, skipping invalid IDs? The clumsy way uses the methods we just warned against:
Stream<User> users = ids.map(Users::lookup)
.filter(Optional::isPresent)
.map(Optional::get);
The elegant way:
Stream<User> users = ids.map(Users::lookup).flatMap(Optional::stream);
Each stream() call yields zero or one users, and flatMap concatenates them all. Missing users vanish.
Many older methods return null instead of an Optional. Suppose Users.classicLookup(id) returns a User or null. Then either filter out the nulls, or use Stream.ofNullable, which plays the same role as Optional::stream:
Stream<User> users = ids.map(Users::classicLookup).filter(Objects::nonNull);
Stream<User> users = ids.map(Users::classicLookup).flatMap(Stream::ofNullable);
A complete example
import java.util.*;
import java.util.stream.*;
public class Solution {
static final Map<String, String> USERS = Map.of("u1", "Ada", "u2", "Grace", "u4", "Linus");
// modern style: return Optional
static Optional<String> lookup(String id) {
return Optional.ofNullable(USERS.get(id));
}
// classic style: return null
static String classicLookup(String id) {
return USERS.get(id);
}
static Optional<Double> inverse(Double x) {
return x == 0 ? Optional.empty() : Optional.of(1 / x);
}
static Optional<Double> squareRoot(Double x) {
return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
}
public static void main(String[] args) {
// creating Optionals
System.out.println("of: " + Optional.of("value"));
System.out.println("ofNullable: " + Optional.ofNullable(null) + ", " + Optional.ofNullable("x"));
System.out.println("empty: " + Optional.empty());
try {
Optional.of(classicLookup("u3"));
} catch (NullPointerException e) {
System.out.println("of(null): NullPointerException");
}
// composing Optional-returning functions with flatMap
System.out.println("inverse(4).flatMap(squareRoot): " + inverse(4.0).flatMap(Solution::squareRoot));
System.out.println("inverse(-1).flatMap(squareRoot): " + inverse(-1.0).flatMap(Solution::squareRoot));
System.out.println("inverse(0).flatMap(squareRoot): " + inverse(0.0).flatMap(Solution::squareRoot));
Optional<Double> chained = Optional.of(0.25).flatMap(Solution::inverse).flatMap(Solution::squareRoot);
System.out.println("chain starting with of(0.25): " + chained);
// map would nest the result
Optional<Optional<Double>> nested = inverse(4.0).map(Solution::squareRoot);
System.out.println("map instead of flatMap: " + nested);
// turning a stream of Optionals into a stream of values
List<String> ids = List.of("u1", "u3", "u2", "u9", "u4");
List<String> users = ids.stream().map(Solution::lookup).flatMap(Optional::stream).toList();
System.out.println("found users: " + users);
// with methods that return null
System.out.println("filter(nonNull): " + ids.stream().map(Solution::classicLookup).filter(Objects::nonNull).toList());
System.out.println("ofNullable: " + ids.stream().map(Solution::classicLookup).flatMap(Stream::ofNullable).toList());
// the anti-patterns and their replacements
Optional<String> maybe = lookup("u2");
if (maybe.isPresent()) System.out.println("isPresent/get: " + maybe.get().length()); // no better than a null check
maybe.map(String::length).ifPresent(len -> System.out.println("map/ifPresent: " + len));
// equality compares contents; identity is meaningless
System.out.println("equals: " + Optional.of("a").equals(Optional.of("a"))
+ ", empty equals empty: " + Optional.empty().equals(Optional.ofNullable(null)));
// Optional is not Serializable
System.out.println("Serializable? " + java.io.Serializable.class.isAssignableFrom(Optional.class));
// primitive optionals from primitive streams
OptionalInt max = IntStream.of(3, 9, 4).max();
OptionalDouble avg = IntStream.empty().average();
System.out.println("OptionalInt " + max.getAsInt() + ", empty average -> " + avg.orElse(Double.NaN));
}
}
of: Optional[value]
ofNullable: Optional.empty, Optional[x]
empty: Optional.empty
of(null): NullPointerException
inverse(4).flatMap(squareRoot): Optional[0.5]
inverse(-1).flatMap(squareRoot): Optional.empty
inverse(0).flatMap(squareRoot): Optional.empty
chain starting with of(0.25): Optional[2.0]
map instead of flatMap: Optional[Optional[0.5]]
found users: [Ada, Grace, Linus]
filter(nonNull): [Ada, Grace, Linus]
ofNullable: [Ada, Grace, Linus]
isPresent/get: 5
map/ifPresent: 5
equals: true, empty equals empty: true
Serializable? false
OptionalInt 9, empty average -> NaN
map with an Optional-returning function produces the nested Optional[Optional[0.5]], which is almost never what you want. flatMap avoids it.
Common questions
Should a repository method like findById return Optional?
Yes. That is the textbook use: the method may legitimately find nothing, and the return type tells callers to handle it. Spring Data, for example, declares Optional<T> findById(ID id). Methods that return collections should instead return an empty collection, never an Optional<List<...>>.
What about Optional in records, DTOs and JSON?
The guideline against Optional fields applies to records too: declare the component as a nullable type, such as String nickname. The accessor nickname() must return exactly that type (a public Optional<String> nickname() is rejected as an invalid accessor method), so if callers benefit from an Optional, add a method with a different name, for example Optional<String> nicknameIfPresent() { return Optional.ofNullable(nickname); }. JSON libraries may need extra support for Optional: Jackson 2.x needs the jackson-datatype-jdk8 module, while Jackson 3 supports it out of the box.
Is @Nullable better than Optional?
They complement each other. Annotations such as JSpecify's @Nullable cost nothing at runtime and work on fields and parameters, but they are checked only by tools (IDEs, static analyzers), not by the compiler. Optional is enforced by the type system but is meant for return values. Many code bases use both: Optional for "maybe no result" returns, annotations everywhere else.
How do I turn an Optional<T> into a list?
optional.stream().toList() gives a list with zero or one element.
How do I combine two Optionals, such as a first name and a last name?
Use flatMap and map: first.flatMap(f -> last.map(l -> f + " " + l)) is present only if both are present.
Why is there no Optional.ifEmpty?
ifPresentOrElse(action, emptyAction) covers that case, and isEmpty() (Java 11) is available for the rare code that really needs a condition.
API reference
java.util.Optional<T>
| Method | Description |
|---|---|
static <T> Optional<T> of(T value) | an Optional holding value; NullPointerException if value is null |
static <T> Optional<T> ofNullable(T value) | of(value) if value isn't null, otherwise empty() |
static <T> Optional<T> empty() | an empty Optional |
<U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> mapper) | the result of mapper applied to the value, or empty |
Stream<T> stream() (Java 9) | a stream of zero or one element |
T get(), T orElseThrow() (Java 10) | the value, or NoSuchElementException if empty |
boolean isPresent(), boolean isEmpty() (Java 11) | whether a value is present or absent |
boolean equals(Object other) | true if other is an Optional with an equal value, or both are empty |
java.util.OptionalInt, OptionalLong, OptionalDouble
| Method | Description |
|---|---|
int getAsInt(), long getAsLong(), double getAsDouble() | the value, or NoSuchElementException |
orElse, orElseGet, orElseThrow, ifPresent, ifPresentOrElse, isPresent, isEmpty, stream() | the same ideas as Optional, for primitives (no map or flatMap) |
Summary
get,isPresentandisEmptyused together are no better thannullchecks. Prefer theorElse,ifPresent,mapandfilterfamily, and spell an intentional unchecked unwraporElseThrow().- Use
Optionalas a return type. Avoid Optional fields, parameters, collection elements and map keys. Never let an Optional variable benull. - Create Optionals with
of(non-null),ofNullable(maybe null) andempty. - Chain Optional-returning functions with
flatMap. The chain is empty if any step is empty. flatMap(Optional::stream)turns a stream of Optionals into a stream of the present values.flatMap(Stream::ofNullable)does the same for nullable values.
Practice Questions
Why is Optional.of(map.get(key)) a bug in most cases, and what should you write?
map.get returns null for a missing key, and Optional.of(null) throws NullPointerException. Use Optional.ofNullable(map.get(key)), which produces an empty Optional for a missing key.
Address.getCity() returns Optional<String>, and User.getAddress() returns Optional<Address>. How do you get the user's city in uppercase, or "UNKNOWN"?
user.getAddress().flatMap(Address::getCity).map(String::toUpperCase).orElse("UNKNOWN"). Use flatMap because getCity returns an Optional, and map because toUpperCase returns a plain String.
You have a List<String> ids and a method Optional<Product> find(String id). Produce a List<Product> of the products that exist.
ids.stream().map(this::find).flatMap(Optional::stream).toList(). Each Optional becomes a stream of zero or one product, and flatMap concatenates them, so missing products are dropped.
What's wrong with a method that is declared to return Optional<Customer> but contains return null; in one branch?
Callers rely on the Optional never being null and call methods like orElse on it directly. The null return causes a NullPointerException in the caller, which is exactly what Optional was meant to prevent. Return Optional.empty() instead.
Why is a field declared as private Optional<String> nickname; discouraged, and what's the usual alternative?
It adds an extra object per field, makes the class non-serializable (Optional isn't Serializable), and invites the field itself to be null. The usual alternative is a nullable field, private String nickname;, with an accessor Optional<String> getNickname() { return Optional.ofNullable(nickname); }.
Previous: Java Optional: Getting, Consuming and Transforming Optional Values
Next: Collecting Java Stream Results: toList, toArray, joining and Summary Statistics
Related reading
- Java Lambda Variable Scope, Processing Lambdas and Comparator Methods
- Java Lambda Expressions and Functional Interfaces
- Java Collectors.toMap: Collecting Streams into Maps
- Collecting Java Stream Results: toList, toArray, joining and Summary Statistics
- Java Optional: Getting, Consuming and Transforming Optional Values

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.