Java Optional: Getting, Consuming and Transforming Optional Values
Use Java's Optional the right way: unwrap with orElse, orElseGet and orElseThrow (and why orElse evaluates eagerly), consume with ifPresent and ifPresentOrElse, and transform with map, filter and or, without ever calling get.
kvi5hnuCode Sprout team member7 min readOn this page
Several stream operations from the previous article (max, min, findFirst, findAny) return an Optional<T>. An Optional<T> is a small wrapper that either holds an object of type T, in which case the value is present, or holds nothing, in which case it's empty. It is meant as a safer alternative to a reference that is either an object or null.
But Optional is only safer if you use it right. Pull the value out with get() without checking, and you've just traded a NullPointerException for a NoSuchElementException. The key idea of this article: work with the Optional through methods that handle both cases. Either produce a fallback when the value is missing, consume the value only if it's there, or keep the Optional and transform what's inside. The next article covers what not to do, how to create Optionals, and how to chain Optional-returning functions.
Strategy 1: get the value, or a fallback
Often there's a sensible default when no value is present:
String result = optionalString.orElse(""); // the wrapped string, or "" if none
If computing the default is expensive or has side effects, pass a function instead. It's called only when needed:
String result = optionalString.orElseGet(() -> System.getProperty("myapp.default"));
Or treat a missing value as an error:
String result = optionalString.orElseThrow(IllegalStateException::new);
String result = optionalString.orElseThrow(() -> new NoSuchUserException(id)); // with a message
The argument is a supplier of an exception, so the exception object is only created when it's actually thrown. Since Java 10, there's also a no-argument orElseThrow(), which throws NoSuchElementException.
Strategy 2: consume the value only if present
ifPresent takes a function and passes it the value if there is one. Otherwise nothing happens:
optionalValue.ifPresent(v -> results.add(v));
optionalValue.ifPresent(results::add); // the same, with a method reference
To do one thing when there's a value and something else when there isn't, use ifPresentOrElse (Java 9):
optionalValue.ifPresentOrElse(
v -> System.out.println("Found " + v),
() -> logger.warning("No match"));
Both return void. They're for actions such as printing, storing or sending. If you want a result, use the methods of the next section.
Strategy 3: transform the value and keep the Optional
map
map applies a function to the value inside an Optional and wraps the result in a new Optional. An empty Optional stays empty, and the function isn't called:
Optional<Path> transformed = optionalString.map(Path::of);
It helps to think of an Optional as a stream of size zero or one. map works exactly like Stream.map: zero elements in, zero out; one element in, one transformed element out.
One subtle rule: if the function returns null, map produces an empty Optional, not an Optional containing null. That makes map handy with methods that signal "nothing" by returning null, such as Map.get:
Optional<String> nickname = Optional.of(name).map(nicknames::get); // empty if there's no nickname
filter
filter keeps the value only if it satisfies a predicate, and otherwise gives an empty Optional:
Optional<Path> textFile = optionalString
.filter(s -> s.endsWith(".txt"))
.map(Path::of);
or
or (Java 9) replaces an empty Optional with another Optional, computed lazily by a supplier. If the original has a value, it's returned unchanged and the supplier isn't called:
Optional<String> result = optionalString.or(() -> alternatives.stream().findFirst());
Compare it with orElseGet. orElseGet unwraps and returns a plain T, while or stays inside the Optional world, so you can keep chaining. A chain of or calls is a clean way to express "try this source, then that one, then a third".
Putting it together
A typical use is reading a setting that may be missing, blank or malformed:
static int setting(Map<String, String> config, String key) {
return Optional.ofNullable(config.get(key)) // the raw string, maybe null
.map(String::strip)
.filter(s -> !s.isEmpty())
.map(Integer::parseInt)
.orElse(-1);
}
Each step only runs if the previous one produced a value. There are no if statements and no null checks, and the code reads top to bottom like a description of the rules. (Optional.ofNullable is explained in the next article. It turns a possibly null reference into an Optional.) A malformed number would still throw NumberFormatException from parseInt. Optional handles absence, not errors.
A complete example
import java.nio.file.Path;
import java.util.*;
public class Solution {
static String expensiveDefault() {
System.out.println(" (computing the default...)");
return "default";
}
static Optional<String> findWord(List<String> words, String part) {
return words.stream().filter(w -> w.contains(part)).findFirst();
}
public static void main(String[] args) {
List<String> words = List.of("Alice", "was", "considering", "red", "roses", "whether", "Fred");
Optional<String> present = findWord(words, "red");
Optional<String> absent = findWord(words, "xyz");
System.out.println("present: " + present + ", absent: " + absent);
// 1. getting a value with a fallback
System.out.println("orElse: " + absent.orElse("N/A"));
System.out.println("orElseGet: " + absent.orElseGet(() -> "computed"));
try {
absent.orElseThrow(() -> new IllegalStateException("no word contains xyz"));
} catch (IllegalStateException e) {
System.out.println("orElseThrow: IllegalStateException: " + e.getMessage());
}
try {
absent.orElseThrow();
} catch (NoSuchElementException e) {
System.out.println("orElseThrow(): NoSuchElementException: " + e.getMessage());
}
// orElse always evaluates its argument, orElseGet only when needed
System.out.println("present.orElse(expensiveDefault()):");
System.out.println(" -> " + present.orElse(expensiveDefault()));
System.out.println("present.orElseGet(Solution::expensiveDefault):");
System.out.println(" -> " + present.orElseGet(Solution::expensiveDefault));
// 2. consuming a value only if present
var results = new TreeSet<String>();
present.ifPresent(results::add);
absent.ifPresent(results::add);
System.out.println("results: " + results);
present.ifPresentOrElse(v -> System.out.println("Found " + v), () -> System.out.println("No match"));
absent.ifPresentOrElse(v -> System.out.println("Found " + v), () -> System.out.println("No match"));
// 3. pipelining: map, filter, or
Optional<Integer> length = present.map(String::length);
System.out.println("map(length): " + length + ", on empty: " + absent.map(String::length));
Optional<Boolean> added = present.map(results::add);
System.out.println("map(results::add): " + added + " (already in the set)");
Optional<String> fileName = Optional.of("notes.txt");
Optional<Path> path = fileName.filter(s -> s.endsWith(".txt")).map(Path::of);
System.out.println("txt path: " + path);
System.out.println("pdf path: " + Optional.of("photo.jpg").filter(s -> s.endsWith(".txt")).map(Path::of));
// map that returns null yields an empty Optional
Map<String, String> nicknames = Map.of("Alice", "Ali");
System.out.println("nickname of Alice: " + Optional.of("Alice").map(nicknames::get));
System.out.println("nickname of Fred: " + Optional.of("Fred").map(nicknames::get));
// or: fall back to another Optional, computed lazily
List<String> alternatives = List.of("backup", "spare");
Optional<String> result = absent.or(() -> alternatives.stream().findFirst());
System.out.println("or: " + result);
System.out.println("or on present: " + present.or(() -> Optional.of("never used")));
// a realistic chain: configuration lookup with fallbacks
Map<String, String> config = Map.of("timeout", " 30 ", "retries", "");
System.out.println("timeout = " + setting(config, "timeout"));
System.out.println("retries = " + setting(config, "retries"));
System.out.println("port = " + setting(config, "port"));
}
static int setting(Map<String, String> config, String key) {
return Optional.ofNullable(config.get(key))
.map(String::strip)
.filter(s -> !s.isEmpty())
.map(Integer::parseInt)
.orElse(-1);
}
}
present: Optional[red], absent: Optional.empty
orElse: N/A
orElseGet: computed
orElseThrow: IllegalStateException: no word contains xyz
orElseThrow(): NoSuchElementException: No value present
present.orElse(expensiveDefault()):
(computing the default...)
-> red
present.orElseGet(Solution::expensiveDefault):
-> red
results: [red]
Found red
No match
map(length): Optional[3], on empty: Optional.empty
map(results::add): Optional[false] (already in the set)
txt path: Optional[notes.txt]
pdf path: Optional.empty
nickname of Alice: Optional[Ali]
nickname of Fred: Optional.empty
or: Optional[backup]
or on present: Optional[red]
timeout = 30
retries = -1
port = -1
present.map(results::add) returns Optional[false] because Set.add returns false when the element was already in the set. The earlier ifPresent(results::add) had already added "red".
Common questions
How do I throw my own exception with a message when the value is missing?
orElseThrow(() -> new UserNotFoundException("No user with id " + id)). The lambda runs only when the Optional is empty, so building the message costs nothing in the normal case.
Can I return a value from ifPresent?
No, ifPresent returns void. To produce a result, use map(...) followed by orElse(...), or orElseGet(...).
What is the difference between Optional.empty() and Optional.ofNullable(null)?
None in behavior; both are empty Optionals. Use empty() when you know there is no value, and ofNullable to wrap a reference that might be null.
How do I compare two Optionals?
With equals: two Optionals are equal if both are empty, or if both hold equal values. Optional.of("a").equals(Optional.of("a")) is true. Never use ==, because Optional is a value-based class.
Does Optional slow my program down?
Each Optional is a small object, and creating one in a method that the JIT compiler inlines usually costs nothing measurable, because escape analysis often removes the allocation. In very hot loops over primitives, prefer OptionalInt and friends, or plain values with a sentinel. Do not avoid Optional for performance reasons without measuring.
Should I check isPresent() before calling orElse?
No. The point of orElse, orElseGet, map and ifPresent is that they handle the empty case for you; an extra check only adds noise.
API reference
java.util.Optional<T> (Java 8)
| Method | Description |
|---|---|
T orElse(T other) | the value, or other if empty; other is always evaluated |
T orElseGet(Supplier<? extends T> other) | the value, or the result of calling other if empty |
<X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) | the value, or throws the supplied exception if empty |
T orElseThrow() (Java 10) | the value, or throws NoSuchElementException if empty |
void ifPresent(Consumer<? super T> action) | passes the value to action if present |
void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) (Java 9) | passes the value to action, or runs emptyAction if empty |
<U> Optional<U> map(Function<? super T, ? extends U> mapper) | an Optional of the function result (empty if the Optional is empty or the result is null) |
Optional<T> filter(Predicate<? super T> predicate) | this Optional if its value satisfies predicate, otherwise empty |
Optional<T> or(Supplier<? extends Optional<? extends T>> supplier) (Java 9) | this Optional if present, otherwise the one produced by supplier |
Summary
- An
Optional<T>holds either a value or nothing. Use it through methods that handle both cases, not throughget(). - Unwrap with
orElse(a cheap default),orElseGet(a computed default) ororElseThrow(absence is an error).orElseevaluates its argument even when the value is present. - Act on a value with
ifPresentorifPresentOrElse. - Transform without unwrapping using
map,filterandor. Think of an Optional as a stream of zero or one elements. Anullresult from themapfunction gives an empty Optional.
Practice Questions
What is printed by Optional.of("x").orElse(log("default")), where log prints its argument and returns it?
default is printed, and then the expression evaluates to "x". Java evaluates method arguments before the call, so log("default") runs even though the Optional has a value. Use orElseGet(() -> log("default")) to avoid that.
What is the difference between orElseGet and or?
orElseGet returns a plain T: the value, or the result of the supplier. or returns an Optional<T>: this Optional if it has a value, or another Optional produced by the supplier. Use or when the fallback is itself optional and you want to keep chaining.
What does Optional.of("key").map(map::get) return when the map has no entry for "key"?
An empty Optional. map::get returns null for a missing key, and Optional.map turns a null function result into Optional.empty().
Rewrite this with Optional methods: String name = opt.isPresent() ? opt.get().toUpperCase() : "UNKNOWN";
String name = opt.map(String::toUpperCase).orElse("UNKNOWN");. map transforms the value if present, and orElse supplies the fallback.
When should you use ifPresent rather than map?
Use ifPresent for an action that produces no result, such as printing a value, adding it to a collection or sending a message. Use map when you want a transformed value, which you then keep as an Optional or unwrap with an orElse method.
Previous: Java Stream Reductions: count, max, min, findFirst, findAny and anyMatch
Next: Java Optional Best Practices: Pitfalls, Creating Optionals, flatMap and stream()
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 Best Practices: Pitfalls, Creating Optionals, flatMap and stream()

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.