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
34

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.
🌐
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).
🌐
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....
🌐
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: ...
🌐
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.
🌐
Baeldung
baeldung.com β€Ί home β€Ί java β€Ί core java β€Ί guide to java optional
Guide To Java Optional | Baeldung
December 8, 2016 - 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(); }
Find elsewhere
🌐
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);
🌐
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.
🌐
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);
Top answer
1 of 10
284

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.

Copy// 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:

Copypublic Optional<String> findMyPhone(int phoneId)

The difference is as below:

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

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

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

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

🌐
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?
December 30, 2022 - 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.
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.

🌐
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 ...
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.

🌐
Medium
medium.com β€Ί @AlexanderObregon β€Ί javas-optional-orelseget-method-explained-d65c97250a9e
Java’s Optional.orElseGet() Explained | Medium
September 27, 2024 - The java.util.Optional class was introduced in Java 8 to help developers deal with null values in a more structured way, minimizing the risk of NullPointerException. One of the key features of the Optional class is its ability to return default values when the value is absent. Two important methods, orElse() and orElseGet(), are used to provide these default values, but they differ in significant ways.
🌐
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 - Returns an Optional describing the given value, if non-null, otherwise returns an empty Optional. ... If a value is present, returns the value, otherwise throws NoSuchElementException. ... The preferred alternative to this method is orElseThrow().