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

Copyopt.ifPresentOrElse(
   value -> System.out.println("Found: " + value),
   () -> System.out.println("Not found")
);
Answer from ZhekaKozlov on Stack Overflow
Top answer
1 of 13
334

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

Copyopt.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:

Copypublic 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:

CopyOptional<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;

Copypublic 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:

CopyConsumer<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<?>>

🌐
Medium
medium.com › @amittoor › fixing-java-8-optional-f347231b0f4a
Fixing Java 8 Optional: ifPresent with else | by Amit Toor | Medium
October 11, 2020 - My other option was to use isPresent() method with if else block (isPresent is different method than ifPresent, isPresent returns a boolean, Just clarification), but it beats the whole purpose of optionals. So I decided to something about it and I ended up writing a wrapper on java optionals. Find code for wrapper class below: ... Once wrapper is defined, we can write our code in the way we intended. Our code now becomes: ... Neat, right? I have implemented orElse and OrElseThrow method for Else logic.
Discussions

When somethings is null: Optional.ofNullable.orElse/ifPresent vs if-else
Optional should only be used as a method return type. You should never wrap a local variable in Optional.ofNullable() just to check if it is null. That makes no sense. The object creation isn't free performance wise and it simply adds nothing. Just do a simple null check with an if statement. More on reddit.com
🌐 r/java
72
33
June 14, 2021
Optional.ifPresent(...).otherwise(...);
Optional has two functions: orElse which takes a parameter type T and returns it if the optional is empty and orElseGet which takes a parameter of a Supplier and will call it if the optional is empty (in case the alternate function has side effects you don't want all the time) More on reddit.com
🌐 r/java
13
9
March 2, 2015
handle exception from Optional's ifPresent

Use .orElseThrow()?

More on reddit.com
🌐 r/learnjava
3
7
January 30, 2020
Why exactly does Brian Goetz not recommend the use of Optional everywhere a value could be null?
The idea with Optional is to force the user of the method to handle the output straight away. Being able to pass that value around is against the point of using an Optional in the first place. For example, you have a method that calls an API. If it returns empty, you should either throw an exception, or fill in some default value. If it returns a value, then unpack it. You should not have an Optional going forward. More on reddit.com
🌐 r/java
285
123
June 2, 2023
🌐
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.
🌐
Jsparrow
jsparrow.github.io › rules › optional-if-present-or-else.html
Use Optional::ifPresentOrElse | jSparrow Documentation
One of the extensions of the Optional API in Java 9 is Optional.ifPresentOrElse, which performs either a Consumer or a Runnable depending on the presence of the value. This rule replaces an 'isPresent' check followed by an else-statement with a single 'ifPresentOrElse' invocation.
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - The ifPresentOrElse() method is created exactly for such scenarios. We can pass a Consumer that will be invoked if the Optional is defined, and a Runnable that will be executed if the Optional is empty.
🌐
DEV Community
dev.to › realnamehidden1_61 › how-does-optionalifpresent-differ-from-optionalorelse-391e
How does Optional.ifPresent() differ from Optional.orElse()? - DEV Community
December 15, 2024 - ... Performing an action (e.g., logging, updating state) if the value exists. Avoiding explicit null checks before acting on a value. ... The orElse() method returns the value contained in the Optional, or a default value if the Optional is empty.
🌐
GeeksforGeeks
geeksforgeeks.org › java › optional-ifpresentorelse-method-in-java-with-examples
Optional ifPresentOrElse() method in Java with examples - GeeksforGeeks
July 12, 2025 - // Java program to demonstrate // Optional.ifPresentOrElse method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println("Optional: " + op); try { // apply ifPresentOrElse op.ifPresentOrElse( (value) -> { System.out.println( "Value is present, its: " + value); }, () -> { System.out.println( "Value is empty"); }); } catch (Exception e) { System.out.println(e); } } } ... Optional: Optional.empty Value is empty Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#ifPresentOrElse-java.util.function.Consumer-java.lang.Runnable-
Find elsewhere
🌐
Java67
java67.com › 2018 › 06 › java-8-optional-example-ispresent-orElse-get.html
Java 8 Optional isPresent(), OrElse() and get() Examples | Java67
You just need to take the literal meaning of Optional that value may or may not be present and you have to code accordingly. This will think you what to do in case of value is not present like using a default value or throwing a proper error message. On a related note, Java is moving really fast and we are already in Java 12, still, a lot of developers have to learn Java 8, particularly the functional programming aspect. If ...
🌐
Hackajob
hackajob.com › talent › blog › using-the-optional-feature-in-java-8
Using the Optional Feature in Java 8
October 9, 2023 - The 'Optional.isPresent' method can be used to check if a value is present within the 'Optional' object. If a value is true, it returns a present, otherwise it returns a false.
🌐
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 - It works in this situation, but it's verbose and provides no improvement over if/else. The point of Optional is to force the caller of a method to handle the empty case, which might get ignored otherwise. From the perspective of the JVM, an Optional is just a normal object assigned to a normal variable. Nothing stops you from passing a null or retuning null in place of an Optional.
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › util › Optional.html
Optional (Java SE 17 & JDK 17)
April 21, 2026 - Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (returns a default value if no value is present) and ifPresent() (performs an action if a value is present). This is a value-based class; programmers should treat instances that are ...
🌐
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 - Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (returns a default value if no value is present) and ifPresent() (performs an action if a value is present). This is a value-based class; programmers should treat instances that are ...
🌐
Medium
medium.com › @AlexanderObregon › javas-optional-ifpresentorelse-method-explained-d60b6414b46e
Java’s Optional.ifPresentOrElse() Explained | Medium
November 7, 2024 - emptyAction: A Runnable that executes if no value is present. Traditionally, checking for null values required verbose if-else blocks. For example: String value = getValue(); if (value != null) { System.out.println("Value: " + value); } else { System.out.println("Value not found."); } With ifPresentOrElse(), this logic becomes much cleaner. Using an Optional object, the code reads as follows: Optional<String> optionalValue = Optional.ofNullable(getValue()); optionalValue.ifPresentOrElse( value -> System.out.println("Value: " + value), () -> System.out.println("Value not found.") ); One of the practical uses of ifPresentOrElse() is handling responses from APIs, where a value might or might not be present.
🌐
Baeldung
baeldung.com › home › java › core java › java optional – orelse() vs orelseget()
Java Optional - orElse() vs orElseGet() | Baeldung
January 16, 2024 - orElseGet(): returns the value if present, otherwise invokes other and returns the result of its invocation · It’s easy to be a bit confused by these simplified definitions, so let’s dig a little deeper and look at some actual usage scenarios. Assuming we have our logger configured properly, let’s start with writing a simple piece of code: String name = Optional.of("baeldung") .orElse(getRandomName());
🌐
W3Docs
w3docs.com › java
Functional style of Java 8's Optional.ifPresent and if-not-Present? | W3Docs
The ifPresent() method (Java 8) ... or contains a value. The ifPresent() method takes a Consumer object as an argument and invokes it with the value contained in the Optional object if it is present....
🌐
Apps Developer Blog
appsdeveloperblog.com › home › java › functional programming in java › optional – ifpresent() and ispresent() methods
Optional - ifPresent() and isPresent() methods - Apps Developer Blog
August 10, 2022 - So the best practice is always to first check if the value is present in the Optional. Example: class Test { public static void main(String[] args) { Optional<String> optional = Optional.ofNullable("someValue"); if (optional.isPresent()) { System.out.println("The value is: " + optional.get()); ...
🌐
Tom Gregory
tomgregory.com › gradle › java-optional
Optional in Java: Everything You Need To Know | Tom Gregory
July 17, 2022 - On an Optional you can call orElse which will either return the value, if present, or otherwise the provided default value.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › util › Optional.html
Optional (Java SE 11 & JDK 11 )
January 20, 2026 - Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (returns a default value if no value is present) and ifPresent() (performs an action if a value is present). This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of Optional may have unpredictable results and should be avoided.
🌐
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 - Optional<String> optional = ... optional.get()); } This method returns true if the Optional object is empty (i.e., it does not contain a value or contains a null value), and false if it contains a non-null value....
🌐
j-labs
j-labs.pl › home › tech blog › how to use and how not to use optional in java
How to use and how not to use Optional in Java | j‑labs
February 11, 2025 - Table table1 = null; Table table2 ... isn’t null so default value will be ignored · orElse(T other) Return the value if present, otherwise return ther....