You can also do:

expectedPackageRepository.findById(1).ifPresent(
    ep -> {
        ep.setDateModified(new Date());
        expectedPackageRepository.saveAndFlush(ep);
    }
);

Ideally, you would also extract the part between brackets ({}) to a separate method. Then, you could write like this:

    expectedPackageRepository.findById(1).ifPresent(this::doSomethingWithEp);

Where:

void doSomethingWithEp(ExpectedPackage ep) {
    ep.setDateModified(new Date());
    expectedPackageRepository.saveAndFlush(ep);
}

You can read the documentation of ifPresent here: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ifPresent-java.util.function.Consumer-

As it states, it will perform the specified action if the value is present and do nothing otherwise.

Answer from Poger on Stack Overflow
Top answer
1 of 4
33

You can also do:

expectedPackageRepository.findById(1).ifPresent(
    ep -> {
        ep.setDateModified(new Date());
        expectedPackageRepository.saveAndFlush(ep);
    }
);

Ideally, you would also extract the part between brackets ({}) to a separate method. Then, you could write like this:

    expectedPackageRepository.findById(1).ifPresent(this::doSomethingWithEp);

Where:

void doSomethingWithEp(ExpectedPackage ep) {
    ep.setDateModified(new Date());
    expectedPackageRepository.saveAndFlush(ep);
}

You can read the documentation of ifPresent here: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ifPresent-java.util.function.Consumer-

As it states, it will perform the specified action if the value is present and do nothing otherwise.

2 of 4
11

Yes, there are other approaches.

If you absolutely expect there always to be a value, then use Optional::orElseThrow to throw an Exception if a null appears.

If you expect a null to possibly arrive, and have an alternative instance available as a fall-back option, use Optional::orElse.

If the fall-back instance is not on hand, but you have a function to call to provide a fall-back instance, use Optional::orElseGet.

If you don’t care about receiving a null, and want to do nothing when a null arrives, use Optional::ifPresent. Pass the block of code to be run if a value arrives.

If you only care if a value arrives that meets some requirement, use Optional::filter. Pass a Predicate defining your requirement. For example, we care only if an Optional< String > contains text and that text has the word purple in it: myOptional.filter( s -> s.contains( "purple" ) ).ifPresent( this::print ) ;. If null received, our desired operation (a call to print in this example) never happens. If a value was received but failed to meet our predicate, our desired operation never happens.


Doing if( myOptional.isPresent() ) { SomeClass x = myOptional.get() ; … } is valid, and safe. But this is not the original intent of Optional as it is basically the same as doing an old-fashioned null-check if ( null == x ) { … }. The other methods on Optional provide a more clear and elegant way to express your intentions towards a possible null arriving.

🌐
Oracle
docs.oracle.com β€Ί javase β€Ί 8 β€Ί docs β€Ί api β€Ί java β€Ί util β€Ί Optional.html
Optional (Java Platform SE 8 )
October 20, 2025 - If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value ...
🌐
Baeldung
baeldung.com β€Ί home β€Ί java β€Ί core java β€Ί java optional – orelse() vs orelseget()
Java Optional - orElse() vs orElseGet() | Baeldung
January 16, 2024 - String name = Optional.of("baeldung") .orElseGet(() -> getRandomName()); The above code won’t invoke the getRandomName() method. Remember (from the Javadoc) that the Supplier method passed as an argument is only executed when an Optional value isn’t present.
🌐
Medium
medium.com β€Ί @AlexanderObregon β€Ί javas-optional-orelse-method-explained-658010699536
Java’s Optional.orElse() Method Explained | Medium
September 7, 2024 - It is a way to avoid ... to null. The orElse() method in the Optional class provides a mechanism to return a default value if the Optional contains no value....
🌐
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 - If I'm writing a API method that returns a value (and it's possible for that value to be null), then I return an Optional instead so whoever uses my API doesn't have to worry about NPE's. I like to think of Optional as a Collection designed to have a single element - I never have methods that return an array - instead I return a Collection, and in place of a case where the array would be null, it's an empty Collection. That same practice holds true for Optional (which again I just think of as a single-element Collection with some nice convenience methods like orElse, orElseGet, and orElseThrow).
🌐
Baeldung
baeldung.com β€Ί home β€Ί java β€Ί core java β€Ί guide to java optional
Guide To Java Optional | Baeldung
January 16, 2024 - Java 10 introduced a simplified no-arg version of orElseThrow() method. In case of an empty Optional it throws a NoSuchElementException: @Test(expected = NoSuchElementException.class) public void whenNoArgOrElseThrowWorks_thenCorrect() { String nullName = null; String name = Optional.ofNullable(nullName).orElseThrow(); }
🌐
Sonar Community
community.sonarsource.com β€Ί rules and languages β€Ί report false-positive / false-negative...
False Positive on `optional.orElse(null)` - Report False-positive / False-negative... - Sonar Community
January 26, 2023 - Version info: Developer Edition, Version 9.4 (build 54424), LGPL v3 what are you trying to achieve: Pass null as an argument to orElse in the Java Optional API: Optional.of( ).map( ).orElse(null) Example of how to replicate the issue in code: ...
Find elsewhere
🌐
Medium
medium.com β€Ί javarevisited β€Ί java-null-handling-with-optionals-b2ded1f48b39
Java - Null Handling With Optionals | by Γ–mer Kurular | Javarevisited | Medium
September 4, 2021 - When you provide a function to the orElse method, it will always run the given method no matter if the value is present inside Optional. For orElseGet method, it will not run the given method if the value is present inside Optional.
🌐
Readthedocs
java-8-tips.readthedocs.io β€Ί en β€Ί stable β€Ί optional.html
10. Handling nulls with Optional β€” Java 8 tips 1.0 documentation
Optional<String> opt = trades.stream() .filter(trade -> "APAC".equals(trade.getRegion())) .findFirst() .map(Trade:::getTradeId); ... Before getting through flatMap method let’s try an example to find the UI certification done by a candidate who is having a job. String certificationName = candidate.getJobProfile() .map(Job::getFramework) .map(Framework::getCertification) .orElse(null);
🌐
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 public String findUserStatus(long id) { Optional<String> status = ... ; // prone to return an empty Optional return status.orElseThrow(IllegalStateException::new); } When you have anOptionaland need anullreference, then use orElse(null).
🌐
Readthedocs
java8tips.readthedocs.io β€Ί en β€Ί stable β€Ί optional.html
10. Handling nulls with Optional β€” Java 8 tips 1.0 documentation
If you notice map & flatMap methods internal implementations, map method will wrap mapper calculated result inside a Optional object where as flatMap method will not. Below snippet is the correct solution for our earlier example. String certificationName = candidate.getJobProfile() .flatMap(Job::getFramework) .flatMap(Framework::getCertification) .orElse(null);
🌐
Baeldung
baeldung.com β€Ί home β€Ί java β€Ί optional orelse optional
Optional orElse Optional in Java | Baeldung
March 17, 2024 - @Test public void givenGuavaOptional_whenNull_thenDefaultText() { assertEquals( com.google.common.base.Optional.of("Name not provided"), Optionals.getOptionalGuavaName(com.google.common.base.Optional.fromNullable(null))); } This was a quick article illustrating how to achieve Optional orElse Optional functionality.
Top answer
1 of 10
283

Short Answer:

  • orElse() will always call the given function whether you want it or not, regardless of Optional.isPresent() value
  • orElseGet() will only call the given function when the Optional.isPresent() == false

In real code, you might want to consider the second approach when the required resource is expensive to get.

// Always get heavy resource
getResource(resourceId).orElse(getHeavyResource()); 

// Get heavy resource when required.
getResource(resourceId).orElseGet(() -> getHeavyResource()) 

For more details, consider the following example with this function:

public Optional<String> findMyPhone(int phoneId)

The difference is as below:

                           X : buyNewExpensivePhone() called

+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+
|           Optional.isPresent()                                   | true | false |
+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+
| findMyPhone(int phoneId).orElse(buyNewExpensivePhone())          |   X  |   X   |
+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+
| findMyPhone(int phoneId).orElseGet(() -> buyNewExpensivePhone()) |      |   X   |
+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+

When optional.isPresent() == false, there is no difference between two ways. However, when optional.isPresent() == true, orElse() always calls the subsequent function whether you want it or not.

Finally, the test case used is as below:

Result:

------------- Scenario 1 - orElse() --------------------
  1.1. Optional.isPresent() == true (Redundant call)
    Going to a very far store to buy a new expensive phone
    Used phone: MyCheapPhone

  1.2. Optional.isPresent() == false
    Going to a very far store to buy a new expensive phone
    Used phone: NewExpensivePhone

------------- Scenario 2 - orElseGet() --------------------
  2.1. Optional.isPresent() == true
    Used phone: MyCheapPhone

  2.2. Optional.isPresent() == false
    Going to a very far store to buy a new expensive phone
    Used phone: NewExpensivePhone

Code:

public class TestOptional {
    public Optional<String> findMyPhone(int phoneId) {
        return phoneId == 10
                ? Optional.of("MyCheapPhone")
                : Optional.empty();
    }

    public String buyNewExpensivePhone() {
        System.out.println("\tGoing to a very far store to buy a new expensive phone");
        return "NewExpensivePhone";
    }


    public static void main(String[] args) {
        TestOptional test = new TestOptional();
        String phone;
        System.out.println("------------- Scenario 1 - orElse() --------------------");
        System.out.println("  1.1. Optional.isPresent() == true (Redundant call)");
        phone = test.findMyPhone(10).orElse(test.buyNewExpensivePhone());
        System.out.println("\tUsed phone: " + phone + "\n");

        System.out.println("  1.2. Optional.isPresent() == false");
        phone = test.findMyPhone(-1).orElse(test.buyNewExpensivePhone());
        System.out.println("\tUsed phone: " + phone + "\n");

        System.out.println("------------- Scenario 2 - orElseGet() --------------------");
        System.out.println("  2.1. Optional.isPresent() == true");
        // Can be written as test::buyNewExpensivePhone
        phone = test.findMyPhone(10).orElseGet(() -> test.buyNewExpensivePhone());
        System.out.println("\tUsed phone: " + phone + "\n");

        System.out.println("  2.2. Optional.isPresent() == false");
        phone = test.findMyPhone(-1).orElseGet(() -> test.buyNewExpensivePhone());
        System.out.println("\tUsed phone: " + phone + "\n");
    }
}
2 of 10
242

Take these two scenarios:

Optional<Foo> opt = ...
Foo x = opt.orElse( new Foo() );
Foo y = opt.orElseGet( Foo::new );

If opt doesn't contain a value, the two are indeed equivalent. But if opt does contain a value, how many Foo objects will be created?

P.s.: of course in this example the difference probably wouldn't be measurable, but if you have to obtain your default value from a remote web service for example, or from a database, it suddenly becomes very important.

🌐
Coderanch
coderanch.com β€Ί t β€Ί 744202 β€Ί java β€Ί Optionals-orElse
Question on Optionals orElse (Java in General forum at Coderanch)
Which means that the orElse will also return an Object, and you're trying to assign to the String variable "name" with no cast. Basically, to get this to work the compiler needs some additional clue that the null should be treated as a String. Here's one way: Another is: ... I believe that ...
🌐
Reddit
reddit.com β€Ί r/java β€Ί why exactly does brian goetz not recommend the use of optional everywhere a value could be null?
r/java on Reddit: Why exactly does Brian Goetz not recommend the use of Optional everywhere a value could be null?
March 25, 2023 - If you have an optional value and... ... you want to simply retrieve its value and nothing else, use orElse(null) which alerts the developer directly that this value might be null.
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί java β€Ί optional-orelse-method-in-java-with-examples
Optional orElse() method in Java with examples - GeeksforGeeks
July 12, 2025 - If there is no value present in this Optional instance, then this method returns the specified value. Below programs illustrate orElse() method: Program 1: ... // Java program to demonstrate // Optional.orElse() method import java.util.*; public ...
Top answer
1 of 6
112

This is part of JDK 9 in the form of method or, which takes a Supplier<Optional<T>>. Your example would then be:

return serviceA(args)
    .or(() -> serviceB(args))
    .or(() -> serviceC(args));

For details see the Javadoc, this post I wrote, or ticket JDK-8080418 where this method was introduced.

2 of 6
70

The cleanest β€œtry services” approach given the current API would be:

Optional<Result> o = Stream.<Supplier<Optional<Result>>>of(
    ()->serviceA(args), 
    ()->serviceB(args), 
    ()->serviceC(args), 
    ()->serviceD(args))
.map(Supplier::get)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();

The important aspect is not the (constant) chain of operations you have to write once but how easy it is to add another service (or modify the list of services in general). Here, adding or removing a single ()->serviceX(args) is enough.

Due to the lazy evaluation of streams, no service will be invoked if a preceding service returned a non-empty Optional.


Starting with Java 9, you can simplify the code to

Optional<Result> o = Stream.<Supplier<Optional<Result>>>of(
    ()->serviceA(args), 
    ()->serviceB(args), 
    ()->serviceC(args), 
    ()->serviceD(args))
.flatMap(s -> s.get().stream())
.findFirst();

though this answer already contains an even simpler approach for JDK 9.

JDK 16 offers the alternative

Optional<Result> o = Stream.<Supplier<Optional<Result>>>of(
    ()->serviceA(args), 
    ()->serviceB(args), 
    ()->serviceC(args), 
    ()->serviceD(args))
.<Result>mapMulti((s,c) -> s.get().ifPresent(c))
.findFirst();

though this approach might be more convenient with service methods accepting a Consumer rather than returning a Supplier.

🌐
Hackajob
hackajob.com β€Ί talent β€Ί blog β€Ί using-the-optional-feature-in-java-8
Using the Optional Feature in Java 8
October 9, 2023 - The following code demonstrates this: ... In this case, the β€˜Optional opNum’ has the value 5 and so this code prints the following output: ... However, if a null β€˜Optional’ is used with the β€˜orElse’ it will return the specified value as ...
Top answer
1 of 2
13

Your usage of nested ifPresent calls is very similar to the (nested) forEach calls on streams, seen in a lot of other questions.

They are a clear sign that you should try better on functional thinking.

What you want to do is

System.out.println(
    Optional.ofNullable(userName) // will be an empty optional if userName is null
            .map(Name::getName)   // will turn to empty optional if getName returns null
            .map("Name is: "::concat) // prepend "Name is: " (only when we have a name)
            .orElse("No Name Found") // get the result string or the alternative
    );

The important point to understand, is, that the mapping steps applied to an empty Optional don’t do anything but return an empty Optional again. Since you want to print in either case, the print statement is not passed as consumer, but written as stand-alone statement, printing the value returned by the orElse invocation, which will be either, the non-null result of the processing steps or the alternative String.

2 of 2
-1

The orElse method allows you to return an alternative value when there isn't one in the Optional.

If you just want to print out an alternative String you can use the orElse method to return an alternative String:

Optional<String> optionalNameString = Optional.ofNullable(value.getName());
System.out.println(optionalNameString.orElse("Name is not present"));

Otherwise you can just check if the value is present using isPresent()

Optional<String> optionalNameString = Optional.ofNullable(value.getName());
if(optionalNameString.isPresent()) {
    // do something
} else {
    //do something else
}