The main design goal of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.

This most closely matches use case #1 in the OP's question. Although, absence of a value is a more precise formulation than null since something like IntStream.findFirst could never return null.


For use case #2, passing an optional argument to a method, this could be made to work, but it's rather clumsy. Suppose you have a method that takes a string followed by an optional second string. Accepting an Optional as the second arg would result in code like this:

foo("bar", Optional.of("baz"));
foo("bar", Optional.empty());

Even accepting null is nicer:

foo("bar", "baz");
foo("bar", null);

Probably the best is to have an overloaded method that accepts a single string argument and provides a default for the second:

foo("bar", "baz");
foo("bar");

This does have limitations, but it's much nicer than either of the above.

Use cases #3 and #4, having an Optional in a class field or in a data structure, is considered a misuse of the API. First, it goes against the main design goal of Optional as stated at the top. Second, it doesn't add any value.

There are three ways to deal with the absence of a value in an Optional: to provide a substitute value, to call a function to provide a substitute value, or to throw an exception. If you're storing into a field, you'd do this at initialization or assignment time. If you're adding values into a list, as the OP mentioned, you have the additional choice of simply not adding the value, thereby "flattening" out absent values.

I'm sure somebody could come up with some contrived cases where they really want to store an Optional in a field or a collection, but in general, it is best to avoid doing this.

Answer from Stuart Marks on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - Sometimes, we may need to get the first non-empty Optional object from a number of Optional objects. In such cases, it would be very convenient to use a method like orElseOptional(). Unfortunately, such operation is not directly supported in Java 8.
Top answer
1 of 14
299

The main design goal of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.

This most closely matches use case #1 in the OP's question. Although, absence of a value is a more precise formulation than null since something like IntStream.findFirst could never return null.


For use case #2, passing an optional argument to a method, this could be made to work, but it's rather clumsy. Suppose you have a method that takes a string followed by an optional second string. Accepting an Optional as the second arg would result in code like this:

foo("bar", Optional.of("baz"));
foo("bar", Optional.empty());

Even accepting null is nicer:

foo("bar", "baz");
foo("bar", null);

Probably the best is to have an overloaded method that accepts a single string argument and provides a default for the second:

foo("bar", "baz");
foo("bar");

This does have limitations, but it's much nicer than either of the above.

Use cases #3 and #4, having an Optional in a class field or in a data structure, is considered a misuse of the API. First, it goes against the main design goal of Optional as stated at the top. Second, it doesn't add any value.

There are three ways to deal with the absence of a value in an Optional: to provide a substitute value, to call a function to provide a substitute value, or to throw an exception. If you're storing into a field, you'd do this at initialization or assignment time. If you're adding values into a list, as the OP mentioned, you have the additional choice of simply not adding the value, thereby "flattening" out absent values.

I'm sure somebody could come up with some contrived cases where they really want to store an Optional in a field or a collection, but in general, it is best to avoid doing this.

2 of 14
139

I'm late to the game but for what it's worth, I want to add my 2 Cents. They go against the design goal of Optional, which is well summarized by Stuart Marks's answer, but I'm still convinced of their validity (obviously).

Use Optional Everywhere

In General

I wrote an entire blog post about using Optional but it basically comes down to this:

  • design your classes to avoid optionality wherever feasibly possible
  • in all remaining cases, the default should be to use Optional instead of null
  • possibly make exceptions for:
    • local variables
    • return values and arguments to private methods
    • performance critical code blocks (no guesses, use a profiler)

The first two exceptions can reduce the perceived overhead of wrapping and unwrapping references in Optional. They are chosen such that a null can never legally pass a boundary from one instance into another.

Note that this will almost never allow Optionals in collections which is almost as bad as nulls. Just don't do it. ;)

Regarding your questions

  1. Yes.
  2. If overloading is no option, yes.
  3. If other approaches (subclassing, decorating, ...) are no option, yes.
  4. Please no!

Advantages

Doing this reduces the presence of nulls in your code base, although it does not eradicate them. But that is not even the main point. There are other important advantages:

Clarifies Intent

Using Optional clearly expresses that the variable is, well, optional. Any reader of your code or consumer of your API will be beaten over the head with the fact that there might be nothing there and that a check is necessary before accessing the value.

Removes Uncertainty

Without Optional the meaning of a null occurrence is unclear. It could be a legal representation of a state (see Map.get) or an implementation error like a missing or failed initialization.

This changes dramatically with the persistent use of Optional. Here, already the occurrence of null signifies the presence of a bug. (Because if the value were allowed to be missing, an Optional would have been used.) This makes debugging a null pointer exception much easier as the question of the meaning of this null is already answered.

More Null Checks

Now that nothing can be null anymore, this can be enforced everywhere. Whether with annotations, assertions or plain checks, you never have to think about whether this argument or that return type can be null. It can't!

Disadvantages

Of course, there is no silver bullet...

Performance

Wrapping values (especially primitives) into an extra instance can degrade performance. In tight loops this might become noticeable or even worse.

Note that the compiler might be able to circumvent the extra reference for short lived lifetimes of Optionals. In Java 10 value types might further reduce or remove the penalty.

Serialization

Optional is not serializable but a workaround is not overly complicated.

Invariance

Due to the invariance of generic types in Java, certain operations become cumbersome when the actual value type is pushed into a generic type argument. An example is given here (see "Parametric polymorphism").

Discussions

Optional Class in Java – A Comprehensive Tutorial
To be fair, i didnt read the whole article but i find the "best practices" and "Common pitfalls" sections to be lack luster. The "overuse of optional" and "use optional only when necessary" seam kind of obvious but its good to write it out. You shouldn't use optional values when the value isn't actually optional. "Avoid Using Optional in Fields or Parameters" why? I heard a senior of mine say a similar thing before and i didn't understand it then and still don't understand it now. Especially since doing exactly that in rust is not only fine but very common. "Returning Optional from Collections" this one i don't understand at all. Collections in Java are already defined interfaces and you couldn't make the `.get()` method return an option if you wanted to. So if im not implementing an existing collections interface, why shouldn't i return an option for those? The big issue for me is that optionals in java are not null safe. A method that returns an optional might not return a value at all but return null instead. So i *should* do a null check for that. Then i use the optional to check if the value is there or not. And then the value inside of the optional might also be null which i should do a null check on. So really if a method returns an optional i *should* check three times if the value is actually there or not. If it had just returned the value i only need to do one null check. Yes there are best practices to make sure that a variable of type Optional is never null. A method that returns optional should never return null and to never put null into an optional but man would it be nice if the language could just guarantee that from the start. More on reddit.com
🌐 r/programming
12
6
October 17, 2024
Using Optional in Java - Backend Chat/Discussions - Devtalk
During a recent code review I came across this scenario: Code in review if (input.getValue() != null) { return Arrays.asList(value); } else { return input.getValues().stream().map(this::parseValues).collect(Collectors.toList()) } And I suggested (in a compassionate way 😁 ) that we use Optional ... More on forum.devtalk.com
🌐 forum.devtalk.com
1
November 16, 2020
Using the Optional class as it's meant to be used
12 recipes but no mention of map or flatMap. Embrace the monad! More on reddit.com
🌐 r/java
113
136
June 23, 2020
Java 8 Optional: What's the Point?
I don't get this guys arguments against Optional. The catch with this new Optional class is of course the word "class". What else could it be? Unless you add another layer to Java's type system, it can only be a reference type or a primitive type. -Throws NullPointerExceptions Of course. In this case the NPE is a programmer error. You're not supposed to put null values inside an Optional container. -Can itself be null, causing a NullPointerException The horse is already out of the barn. Optional is a reference type and thus can technically be null. Don't return null where Optional is declared. -Increases heap size Are you sure about that? The JVM doesn't always heap allocate, and for very small types, it might not even stack allocate, using registers directly. -Makes debugging more difficult Null makes debugging difficult. Why is that value null? Better trace the call graph. A reference is a box, either containing a value or a bomb, but there's no label on the box. So, you always to look inside the box to make sure it's safe or just trust that the box doesn't have a bomb inside. At least Optional puts a label on the box, and if you code with the convention that potentially empty values are wrapped in Optional, then you can better trust that in all other cases raw references aren't bombs. -Makes serializing objects, say as an XML or JSON for an external client, much more difficult Why on earth would you do this? You should serialize the thing inside optional, not optional itself. More on reddit.com
🌐 r/java
4
0
May 14, 2014
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-8-optional-class
Java 8 Optional Class - GeeksforGeeks
May 16, 2026 - In the following example, we are using Optional. So, our program can execute without crashing. ... import java.util.Optional; // Driver Class public class OptionalDemo { // Main Method public static void main(String[] args) { String[] words = new String[10]; Optional<String> checkNull = Optional.ofNullable(words[5]); if (checkNull.isPresent()) { String word = words[5].toLowerCase(); System.out.print(word); } else System.out.println("word is null"); } }
🌐
Medium
medium.com › @uvrajanshuman › optional-in-java-8-ffcf45e01602
Optional in Java 8. Optional is a generic class defined in… | by Anshuman Yuvraj | Medium
October 2, 2023 - Optional<String> optionalName = Optional.empty(); String name = optionalName .orElseThrow(() -> new IllegalArgumentException("Name is absent")); ... Exception in thread "main" java.lang.IllegalArgumentException: Name is absent .....
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
April 21, 2026 - This method supports post-processing on optional values, without the need to explicitly check for a return status. For example, the following code traverses a stream of file names, selects one that has not yet been processed, and then opens that file, returning an Optional<FileInputStream>:
🌐
DEV Community
dev.to › ivangavlik › how-to-use-the-optional-class-java-3pf5
How to use Optional class (Java) - best practices - DEV Community
January 27, 2024 - Optional is limited mechanism for library method return types where there needed to be a clear way to represent "no result", and using null for such was overwhelmingly likely to cause errors. For example, you probably should never use it for something that returns an array of results, or a list of results; instead return an empty array or list.
Find elsewhere
🌐
Reddit
reddit.com › r/programming › optional class in java – a comprehensive tutorial
r/programming on Reddit: Optional Class in Java – A Comprehensive Tutorial
October 17, 2024 - The big issue for me is that optionals in java are not null safe. A method that returns an optional might not return a value at all but return null instead. So i *should* do a null check for that. Then i use the optional to check if the value is there or not.
🌐
LinkedIn
linkedin.com › pulse › optional-java-8-example-terala-chittibabu
Optional in Java 8 with example
July 12, 2022 - If the Optional contains a value, then it returns the same Optional otherwise it returns another default Optional object. or expects an argument of type java.util.function.Supplier.
🌐
Medium
medium.com › @JavaFusion › the-optional-class-in-java-8-469490077c0b
The Optional class in Java 8. The Optional class was introduced in… | by Java Fusion | Medium
April 1, 2024 - In this bellow example, the lambda ... (“value” in this case). ... Optional<String> optional = Optional.of("value"); optional.ifPresent(val -> System.out.println("Value is present: " + val)); This method was introduced in ...
🌐
GitHub
gist.github.com › carefree-ladka › cc6426829c8865a45f727db7368e94fe
Complete Java Optional Guide with Best Practices · GitHub
Optional.empty() // Empty Optional Optional.of(value) // ⚠️ Throws NPE if null Optional.ofNullable(value) // ✅ Safe, recommended · isPresent() // true if value present isEmpty() // true if empty (Java 11+) get() // ⚠️ Throws exception if empty orElse(default) // Return default if empty orElseGet(supplier) // ✅ Lazy default orElseThrow() // Throw exception orElseThrow(supplier) // Custom exception ·
🌐
Baeldung
baeldung.com › home › java › optional orelse optional
Optional orElse Optional in Java | Baeldung
March 17, 2024 - Java 9 has added an or() method that we can use to get an Optional, or another value, if that Optional isn’t present. Let’s see this in practice with a quick example:
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › guide to java 8 optional
Java 8 Optional (with Examples) - HowToDoInJava
February 7, 2023 - In this Java tutorial, we will discuss one of Java 8 features i.e. Optional that are recommended to minimize the issues occurred when null is used. In Java, we use a reference type to gain access to an object, and when we don’t have a specific object to make our reference point to, then we set such references to null to imply the absence of a value. The use of null is so common that we rarely put more thought into it. For example, field members of objects are automatically initialized to null, and programmers typically initialize reference types to null when they don’t have an initial value to give them.
🌐
Javacodehouse
javacodehouse.com › blog › java-optional-use
Java Optional | How and When to use it
Optional integrates well with the Stream API. For example, you can use Optional in combination with filter, map, and other stream operations.
🌐
Devtalk
forum.devtalk.com › backend developer forum › backend chat/discussions
Using Optional in Java - Backend Chat/Discussions - Devtalk
November 16, 2020 - During a recent code review I came across this scenario: Code in review if (input.getValue() != null) { return Arrays.asList(value); } else { return input.getValues().stream().map(this::parseValues).collect(Collectors.toList()) } And I suggested (in a compassionate way 😁 ) that we use Optional to treat the null value, so my suggestion was something like: return Optional.ofNullable(input.getValue()).map(Arrays::asList) .orElseGet(input.getValues().stream().map(this::parseVa...
🌐
Reddit
reddit.com › r/java › using the optional class as it's meant to be used
r/java on Reddit: Using the Optional class as it's meant to be used
June 23, 2020 - I've seen people argue that you ... even use Optional without streams. I have no idea how they'd get that impression but hey, some people think it. It does feel like some Java APIs since Java 8 have been trying to force you to use lambdas. ModuleReader doesn't return an array of elements but instead a stream via a poorly named list() method, for example...
🌐
Open Graph
ogp.me
The Open Graph protocol
OpenGraph for Java - Small Java class used to represent the Open Graph protocol.
🌐
Medium
medium.com › javarevisited › optional-class-in-java-8-making-your-code-more-clear-and-concise-62af0712910d
Optional Class in Java 8: Making Your Code More Clear and Concise . | by Hamza Nassour | Javarevisited | Medium
May 29, 2024 - Of course, there are still if-else blocks in this logic, but let’s examine other useful methods provided by the Optional API to reduce its use.Of course, there are still if-else blocks in this logic, but let’s examine other useful methods provided by the Optional API to reduce its use. ... orElse is a method in the Java Optional class that is used to return the value wrapped in the Optional, if it is present, or a default value if it is not.
🌐
Java Guides
javaguides.net › 2018 › 07 › java-8-optional-class.html
Java 8 Optional Class with Examples
August 11, 2021 - Optional.empty() method is useful to create an empty Optional object. import java.util.Optional; public class OptionalBasicExample { public static void main(String[] args) { Optional<String> gender = Optional.of("MALE"); String answer1 = "Yes"; String answer2 = null; System.out.println("Non-Empty Optional:" + gender); System.out.println("Non-Empty Optional: Gender value : " + gender.get()); System.out.println("Empty Optional: " + Optional.empty()); System.out.println("ofNullable on Non-Empty Optional: " + Optional.ofNullable(answer1)); System.out.println("ofNullable on Empty Optional: " + Optional.ofNullable(answer2)); // java.lang.NullPointerException System.out.println("ofNullable on Non-Empty Optional: " + Optional.of(answer2)); } }
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.6 documentation
A match statement takes an expression and compares its value to successive patterns given as one or more case blocks. This is superficially similar to a switch statement in C, Java or JavaScript (and many other languages), but it’s more similar to pattern matching in languages like Rust or Haskell.