Java Optional guide: creation, chaining, best practices, anti-patterns, and when to use Optional vs null.
Optionals: Avoiding NullPointerException
Optional<T> is a container that may or may not hold a value. It forces callers to
explicitly handle the "no value" case instead of silently passing null around until
something throws a NullPointerException.
Quick start
Creating Optionals
Use
Optional.of()when you are certain the value is non-null. UseOptional.ofNullable()when the value might be null.
Unwrapping values
Safe unwrapping
Avoid: get() without checking
Chaining operations
map
Transform the value if present:
flatMap
Use when the transformation itself returns an Optional (avoids Optional<Optional<T>>):
filter
Keep the value only if it matches a predicate:
or (Java 9+)
Provide an alternative Optional if empty:
stream (Java 9+)
Convert to a Stream (0 or 1 elements), useful in stream pipelines:
Chaining example: user profile lookup
Optional with streams
Optional vs null: when to use which
Rule of thumb
- Return
Optionalfrom methods that might not have a result - Accept
null(not Optional) in method parameters - use@Nullableannotation - Never store Optional as a field (it is not
Serializableand adds overhead) - Never use Optional in collections (
List<Optional<String>>is a code smell)