You could use a filter:

Optional.ofNullable(s).filter(not(String::isEmpty));

That will return an empty Optional if ppo is null or empty.

Answer from assylias on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - Let’s now look at how the above code could be refactored in Java 8. In typical functional programming style, we can execute perform an action on an object that is actually present: @Test public void givenOptional_whenIfPresentWorks_thenCorrect() { Optional<String> opt = Optional.of("baeldung"); opt.ifPresent(name -> System.out.println(name.length())); } In the above example, we use only two lines of code to replace the five that worked in the first example: one line to wrap the object into an Optional object and the next to perform implicit validation as well as execute the code.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
April 21, 2026 - Indicates whether some other object is "equal to" this Optional. The other object is considered equal if: ... Returns the hash code value of the present value, if any, or 0 (zero) if no value is present. ... Returns a non-empty string representation of this Optional suitable for debugging.
🌐
Mkyong
mkyong.com › home › java8 › java 8 – convert optional to string
Java 8 - Convert Optional<String> to String - Mkyong.com
February 23, 2020 - In Java 8, we can use .map(Object::toString) to convert an Optional<String> to a String.
🌐
Medium
medium.com › @nweligalla › optional-in-java-8-5fbf12c90bfe
Optional in Java 8. Java Optional, introduced in Java 8… | by Nayana Weligalla | Medium
January 23, 2024 - Let’s rewrite the getText() function using Java Optional. There are two ways to create an Optional object with a value ‘Hello World. //option 1 Optional<String> text = Optional.ofNullable("Hello World");
🌐
GeeksforGeeks
geeksforgeeks.org › java › optional-tostring-method-in-java-with-examples
Optional toString() method in Java with examples - GeeksforGeeks
July 12, 2025 - Below programs illustrate toString() method: Program 1: ... // Java program to demonstrate // Optional.toString() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op ...
🌐
Laulem
laulem.com › en › dev › optional-usage-java-tutorial.html
Guide To Java Optional - LauLem.com
November 7, 2024 - String element = "Alex"; Optional<String> myOptional = Optional.ofNullable(element); Optional<String> myOptional2 = Optional.ofNullable(null); Note: This method is preferable because it is null-safe. After creating an Optional, we can check if it is empty or not (value contained is null) using the isEmpty method (from Java 11) and isPresent.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-8-optional-class
Java 8 Optional Class - GeeksforGeeks
May 16, 2026 - Then, Optional.of(str[2]) creates an Optional that contains a non-null string. The print statements display an empty Optional and an Optional holding a value, showing how Optional safely represents both cases.
🌐
Medium
medium.com › walmartglobaltech › true-power-of-optional-in-java-306a77c62d00
True power of Optional in Java. Optional in Java is a container for an… | by Ginoy George | Walmart Global Tech Blog | Medium
July 19, 2021 - In this case, if the patronName contained a non-null value, that value will be printed, otherwise, the string ‘Anonymous’ will be printed. Isn’t this more concise than the null-check way? You can find many more examples of using Optional on the web, so let me focus on some of the anti-patterns of using Optional here.
🌐
Medium
medium.com › @pratik.941 › mastering-optional-in-java-8-a-comprehensive-guide-3131eac600dc
Mastering optional in Java 8: A Comprehensive Guide | by Pratik T | Medium
May 30, 2024 - - Description: If a value is present, returns an `Optional` describing the value, otherwise returns an `Optional` produced by the supplying function. - Use Case: To provide an alternative `Optional` if the current one is empty.
🌐
Develpreneur
develpreneur.com › home › introduction to the java optional class
Introduction to the Java Optional Class
November 15, 2022 - So this time, in the above code, we create a new Optional<String> for both the variable and method getName.
🌐
BeginnersBook
beginnersbook.com › 2017 › 10 › java-8-optional-class
Java 8 Optional Class
September 11, 2022 - public class Example { public static ... System.out.print(str2); } } ... Optional.ofNullable() method of the Optional class, returns a Non-empty Optional if the given object has a value, otherwise it returns an empty Optional....
🌐
Hackajob
hackajob.com › talent › blog › using-the-optional-feature-in-java-8
Using the Optional Feature in Java 8
October 9, 2023 - In the example above, an ‘Optional String opStr’ is created with the text “Hello World”. A lambda expression is specified in the ‘ifPresent’ method that simply prints the input value.
🌐
DEV Community
dev.to › sohailshah › using-optionals-in-java-the-right-way-4aho
Using Optional in Java the right way - DEV Community
August 21, 2023 - Java //returning a empty optional of type string public static Optional<String> emptyOptional(){ return Optional.empty(); } //or Optional<String> str = Optional.empty(); Using the Optional.ofNullable() method we can create nullable optional objects. These objects can be null or have values in them ·
🌐
Baeldung
baeldung.com › home › java › java string › transforming an empty string into an empty optional
Transforming Empty Strings into Empty Optionals | Baeldung
February 20, 2026 - In Java 11, we’ll still use Optional.filter(), but Java 11 introduces a new Predicate.not() API that makes it easy to negate method references. So, let’s simplify what we did earlier, now using a method reference instead: @Test public void givenEmptyString_whenFilteringOnOptionalInJava11_thenEmptyOptionalIsReturned() { String str = ""; Optional<String> opt = Optional.ofNullable(str).filter(Predicate.not(String::isEmpty)); Assert.assertFalse(opt.isPresent()); }
Top answer
1 of 4
5

Whether something is "OK to use" depends on intent, team coding practices, common programming idioms, and how strictly you want to adhere to API guidelines.

First, the facts about Optional<T>:

A container object which may or may not contain a non-null value.

...

API Note:

Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors. A variable whose type is Optional should never itself be null; it should always point to an Optional instance.

Source: Oracle Java 11 JDK documentation (emphasis, mine)

Not a lot of concrete guidance here beyond the recommendation that Optional<T> be used as a return type. In a strict sense, you are not using this as a return type, therefore the answer is "no, this is not OK." On the other hand, you are using it as the type for a field which may contain null. So you seem to satisfy the first part.

But it works.

That's why it's important to remember these are guidelines. The mechanics of whether you can use something are a different discussion, and hence, your question. Instead, I like to see how these optional fields are being used to ensure a more suitable OO design doesn't already exist.

If I had to look at a codebase that was peppered with field.ifPresent(foo -> foo.method()) every time field was used, I would start to wonder if we have a design problem with field rather than it's type. Even in cases where you have field.isPresentOrElse(foo -> foo.method(), () -> something else), I still think we are missing something. Frankly, the constant calls to the Optional<T> methods as a round-about way to avoid NullPointerExceptions makes me think the Null Object Pattern might be a better choice here. Every method in the "null object" can be a no-op. Getters can return pre-canned values (whatever the "or else" part of Optional.ifPresentOrElse() would have returned).

I don' like optional dependencies because they can be null, so now I need to incessantly check for null, or I need to use some other non-idiomatic construct like Optional<T> with a bunch of pass-through method calls in lieu of null-checks.

Code is much cleaner if you can simply call field.method() rather than field.ifPresent(foo -> foo.method()).

Some additional notes:

  • The guidance in this answer applies best to situations where the T is a complex type. When T is a string, boolean, or numeric type, then the "optional" part of an Optional<T> becomes meaningful. An Optional<boolean> can be true, false, or not present, which your application could interpret as "not specified." In that case, document this fact on the field.

    • In the case of a String, consider defaulting to an empty string instead. No need for null if you have proper encapsulation. A constructor or setter can enforce the "empty string instead of null" constraint.
  • When T is a complex type, consider other, more straight-forward designs first before resorting to an Optional<T>, if for no other reason than the Principle of Least Astonishment.

  • Choose code that is easy to read first. In situations like this, I like to write the same code multiple ways. Consider writing it when checking for nulls, using another more suitable design pattern (like Null Object Pattern), and using an optional. Same code. 3 different styles. Which one do you like?

    • And then present the same 3 styles to a colleague to see which one they like.

In the end, you get working code either way. Personal taste, other object-oriented design practices and team habits play a bigger role in this decision than API guidance.

2 of 4
5

Optional is now intended to be used as a Monad. Java designers effectively admitted that by adding Optional.stream() method.

Ignore earlier discussions about:

  • serialization. Serialization should not be used in new code
  • library interfaces. They are not different from your own.
  • method argument. Using Optional as argument in much more idiomatic than doing a conditional dispatch over method overloads.

Surprisingly, important reasons not to use an Optional as a field are:

  • memory consumption - it increases the size of your field up to 4 times.
  • performance - it introduces additional memory indirection

These are only applicable to long-lived numerous objects (example: gamedev).

🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › util › Optional.html
Optional (Java SE 21 & JDK 21)
January 20, 2026 - Indicates whether some other object is "equal to" this Optional. The other object is considered equal if: ... Returns the hash code of the value, if present, otherwise 0 (zero) if no value is present. ... Returns a non-empty string representation of this Optional suitable for debugging.
🌐
javathinking
javathinking.com › blog › converting-options-string-to-string-java
Converting Optional String to String in Java — javathinking.com
It is a container object which may or may not contain a non-null value. When dealing with strings, you might often encounter situations where you have an Optional<String> and need to convert it to a regular String.