You could use orElse(null):

String o = getOptional().orElse(null);
if (o == null) {
    return;
}
Answer from dnault on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
January 16, 2024 - Note that we used the isPresent() method to check if there is a value inside the Optional object. A value is present only if we have created Optional with a non-null value.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
October 20, 2025 - Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional. ... If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException. ... Return true if there is a value present, otherwise false.
🌐
Reddit
reddit.com › r/java › why does optional require a non-null value?
r/java on Reddit: Why does Optional require a non-null value?
June 13, 2024 -

Since the whole purpose of Optional is to represent values that might not exist, why does the constructor of Optional require a non-null value? Is it becuase they wanted to coalesce all empty Optionals down to a single instance? Even if that's true, why not make Optional.of() behave the way Optional.ofNullable() and do away with the ofNullable() method?

Edit to clarify my opinion and respond to some of the points raised:

My opinion stated clearly, is only two "constructor" methods should exist:

  • of (and it should work like the current ofNullable method)

  • empty

So far the arguments against my opinion have been:

  1. Having .of() and .ofNullable() makes it clear at the point of construction when the value exists and when it might not exist.

This is true, but that clarity is redundant. For safety, the call to .of() will either be inside the not-null branch of a null-check, or come after a not-null assertion. So even if .of() behaved as .ofNullable() does it would be clear that the value exists.

2. It guards against changes in behavior of the the methods supplying the values. If one of the supplying methods suddenly changes from never returning nulls to sometime returning nulls it will catch the error.

I would argue that guarding against this occurrence is the responsibility of the function returning the Optional values, and not the responsibility of Optional. If the function needs to guard against a null value so that it can handle it in some fashion (eg. by calling another supplier method) then then it needs to implement the not-null assertion explicitly in the body of its code. This is more clear than relying on an class called Optional do something that is semantically at odds with the plain reading of its class name.

In the case where the function doesn't care whether the value returned from the supplier is null or not, it should simply be able to call .of() to create the optional and return it.

🌐
Medium
medium.com › javarevisited › java-null-handling-with-optionals-b2ded1f48b39
Java - Null Handling With Optionals | by Ömer Kurular | Javarevisited | Medium
September 4, 2021 - As you see, stringOptionalNull is an empty Optional and we provide a backup value in case it is not present thanks to orElse method. So, it prints the value given to orElse method. orElseGet(Supplier<? extends T> other), returns the value inside Optional if present, otherwise runs the supplied logic and then returns its result.
🌐
Readthedocs
java8tips.readthedocs.io › en › stable › optional.html
10. Handling nulls with Optional — Java 8 tips 1.0 documentation
Scala has a safe way to navigate through values, Google’s Guava library and Groovy language has same construct as Java Optional, so you can assume java Optional is inspired from them. Optional provides three basic methods: map, flatMap and filter to perform any kind of common task. Like Streams these operations can also be chained togather to perform composite tasks. ... If a value is present, apply the provided mapping function to it, and return an Optional describing the result, otherwise return an empty Optional.
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Return Optional not null
*/ public Human(String name, String address, Set<Human> friends, LocalDate birthDate){ this.name = Objects.requireNonNull(name).trim(); if (this.name.length() == 0){ throw new IllegalArgumentException("Name is empty."); } this.address = Objects.requireNonNull(address).trim(); this.friends.addAll(Objects.requireNonNull(friends)); //defensive copy this.birthDate = birthDate; //immutable, no need to copy } //..elided /** Never null or empty. */ public String getName() { return name; } /** Might be an empty String. */ public String getAddress() { return address; } /** Might be an empty Set. */ public Set<Human> getFriends() { //make sure the caller can't modify the private Set return Collections.unmodifiableSet(friends); } /** May or may not be present. The returned Optional object is itself never null!
Find elsewhere
Top answer
1 of 13
333

If you are using Java 9+, you can use ifPresentOrElse() method:

opt.ifPresentOrElse(
   value -> System.out.println("Found: " + value),
   () -> System.out.println("Not found")
);
2 of 13
129

For me the answer of @Dane White is OK, first I did not like using Runnable but I could not find any alternatives.

Here another implementation I preferred more:

public class OptionalConsumer<T> {
    private Optional<T> optional;

    private OptionalConsumer(Optional<T> optional) {
        this.optional = optional;
    }

    public static <T> OptionalConsumer<T> of(Optional<T> optional) {
        return new OptionalConsumer<>(optional);
    }

    public OptionalConsumer<T> ifPresent(Consumer<T> c) {
        optional.ifPresent(c);
        return this;
    }

    public OptionalConsumer<T> ifNotPresent(Runnable r) {
        if (!optional.isPresent()) {
            r.run();
        }
        return this;
    }
}

Then:

Optional<Any> o = Optional.of(...);
OptionalConsumer.of(o).ifPresent(s -> System.out.println("isPresent " + s))
                .ifNotPresent(() -> System.out.println("! isPresent"));

Update 1:

the above solution for the traditional way of development when you have the value and want to process it but what if I want to define the functionality and the execution will be then, check below enhancement;

public class OptionalConsumer<T> implements Consumer<Optional<T>> {
private final Consumer<T> c;
private final Runnable r;

public OptionalConsumer(Consumer<T> c, Runnable r) {
    super();
    this.c = c;
    this.r = r;
}

public static <T> OptionalConsumer<T> of(Consumer<T> c, Runnable r) {
    return new OptionalConsumer(c, r);
}

@Override
public void accept(Optional<T> t) {
    if (t.isPresent()) {
        c.accept(t.get());
    }
    else {
        r.run();
    }
}

Then could be used as:

Consumer<Optional<Integer>> c = OptionalConsumer.of(
    System.out::println, 
    () -> System.out.println("Not fit")
);

IntStream.range(0, 100)
    .boxed()
    .map(i -> Optional.of(i)
    .filter(j -> j % 2 == 0))
    .forEach(c);

In this new code you have 3 things:

  1. can define the functionality before the existing of an object easy.
  2. not creating object reference for each Optional, only one, you have so less memory than less GC.
  3. it is implementing consumer for better usage with other components.

By the way, now its name is more descriptive it is actually Consumer<Optional<?>>

🌐
DZone
dzone.com › coding › languages › 26 reasons why using optional correctly is not optional
26 Reasons Why Using Optional Correctly Is Not Optional
November 28, 2018 - // PREFER Product product = new Product(); Optional<Product> op1 = Optional.of(product); Optional<Product> op2 = Optional.of(product); // op1.equals(op2) => true,expected true if (op1.equals(op2)) { ... ... Starting with Java 11, we can easily return atrueif anOptionalis empty via theisEmpty()method. ... // AVOID (Java 11+) public Optional<String> fetchCartItems(long id) { Cart cart = ... ; // this may be null ...
Top answer
1 of 9
23

Optional harnesses the type system for doing work that you'd otherwise have to do all in your head: remembering whether or not a given reference may be null. This is good. It's always smart to let the compiler handle boring drugework, and reserve human thought for creative, interesting work.

Without Optional, every reference in your code is like an unexploded bomb. Accessing it may do something useful, or else it may terminate your program wth an exception.

With Optional and without null, every access to a normal reference succeeds, and every reference to an Optional succeeds unless it's unset and you failed to check for that. That is a huge win in maintainability.

Unfortunately, most languages that now offer Optional haven't abolished null, so you can only profit from the concept by instituting a strict policy of "absolutely no null, ever". Therefore, Optional in e.g. Java is not as compelling as it should ideally be.

2 of 9
23

An Optional brings stronger typing into operations that may fail, as the other answers have covered, but that is far from the most interesting or valuable thing Optionals bring to the table. Much more useful is the ability to delay or avoid checking for failure, and to easily compose many operations that may fail.

Consider if you had your optional variable from your example code, then you had to perform two additional steps that each might potentially fail. If any step along the way fails, you want to return a default value instead. Using Optionals correctly, you end up with something like this:

return optional.flatMap(x -> x.anotherOptionalStep())
               .flatMap(x -> x.yetAnotherOptionalStep())
               .orElse(defaultValue);

With null I would have had to check three times for null before proceeding, which adds a lot of complexity and maintenance headaches to the code. Optionals have that check built in to the flatMap and orElse functions.

Note I didn't call isPresent once, which you should think of as a code smell when using Optionals. That doesn't necessarily mean you should never use isPresent, just that you should heavily scrutinize any code that does, to see if there is a better way. Otherwise, you're right, you're only getting a marginal type safety benefit over using null.

Also note that I'm not as worried about encapsulating this all into one function, in order to protect other parts of my code from null pointers from intermediate results. If it makes more sense to have my .orElse(defaultValue) in another function for example, I have much fewer qualms about putting it there, and it's much easier to compose the operations between different functions as needed.

🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › util › Optional.html
Optional (Java SE 17 & JDK 17)
October 20, 2025 - ... NullPointerException - if a value is present and the given action is null, or no value is present and the given empty-based action is null. ... If a value is present, and the value matches the given predicate, returns an Optional describing the value, otherwise returns an empty Optional.
🌐
Medium
medium.com › thefreshwrites › java-optional-and-either-handling-null-values-and-representing-two-possible-values-6a477a0fe189
Java Optional and Either: Handling Null Values and Representing Two Possible Values | by Samuel Catalano | Mar, 2023 | Medium | The Fresh Writes
March 10, 2023 - In this example, optionalName is an Optional that contains a value if name is not null, otherwise it is empty. The orElse() method returns the value if it is present, otherwise it returns the default value “Unknown”. Java Either is a class ...
🌐
Readthedocs
java-8-tips.readthedocs.io › en › stable › optional.html
10. Handling nulls with Optional — Java 8 tips 1.0 documentation
Scala has a safe way to navigate through values, Google’s Guava library and Groovy language has same construct as Java Optional, so we can say java Optional can be inspired from them. Optional provides three basic methods: map, flatMap and filter to perform any kind of common task. Like Streams these operations can also be chained togather to perform composite tasks. ... If a value is present, apply the provided mapping function to it, and return an Optional describing the result, otherwise return an empty Optional.
🌐
Foojay
foojay.io › home › optional in java: a swiss army knife for handling nulls and improving code quality
Optional in Java: A Swiss Army Knife for Handling Nulls and Improving Code Quality
February 20, 2023 - In this example, we create an Optional from a potentially null value, and use Optional.map() to perform a transformation on the value only if it is present. This avoids the need for an if statement to check for null, and makes the code more concise and readable. Optional can be used to compose methods together more concisely and expressively. By wrapping the return value of a method in an Optional, you can use Optional methods to chain multiple methods calls together.
🌐
Hackajob
hackajob.com › talent › blog › using-the-optional-feature-in-java-8
Using the Optional Feature in Java 8
October 9, 2023 - If the code that invokes the method expects a non-null value, this can result in a ‘NullPointerException’. To avoid this, you’ll need to add explicit null checks in your code, which can make the overall script difficult to read.
🌐
Medium
medium.com › @reetesh043 › java-optional-avoiding-null-pointer-exceptions-made-easy-d44e34b7c3e1
Java Optional: Avoiding Null Pointer Exceptions Made Easy | by Reetesh Kumar | Medium
February 9, 2024 - String nullableValue = null; ... to check for the presence of a value: isPresent(): This method returns true if the Optional object contains a value, and false if it does not....
🌐
Reddit
reddit.com › r/java › when somethings is null: optional.ofnullable.orelse/ifpresent vs if-else
When somethings is null: Optional.ofNullable.orElse/ifPresent vs if-else : r/java
June 14, 2021 - There is no reason to prefer not Optional over Optional as the return type of a getter for a nullable field of a POJO. The internal field is just the type. Your getter/setter pair is just Optional<T> getT() and void setT(T t) Well that violates the Java Bean Properties spec unless of course you provide a setter of void setT(Optional<T>). I'm fairly sure a whole bunch of tools will fail on that. I still think in most cases (not all cases) Optional is worse than null particularly if a code base is using a null type checker like Checker.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › › › java.base › java › util › Optional.html
Optional (Java SE 11 & JDK 11 )
October 20, 2025 - ... NullPointerException - if a value is present and the given action is null, or no value is present and the given empty-based action is null. ... If a value is present, and the value matches the given predicate, returns an Optional describing the value, otherwise returns an empty Optional.