DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How To Create a Stub in 5 Minutes
  • Commonly Occurring Errors in Microsoft Graph Integrations and How to Troubleshoot Them (Part 3)
  • Linked List Popular Problems Vol. 1
  • Coordinating Threads Using CountDownLatch

Trending

  • Self-Hosted Inference Doesn’t Have to Be a Nightmare: How to Use GPUStack
  • Scaling Cloud Data Automation: A Practical Guide to Open Table Formats
  • Zone-Free Angular: Unlocking High-Performance Change Detection With Signals and Modern Reactivity
  • Run Gemma 4 on Your Laptop: A Hands-On Guide to Google's Latest Open Multimodal LLM
  1. DZone
  2. Coding
  3. Java
  4. Optional.orElse() Vs. Optional.orElseGet()

Optional.orElse() Vs. Optional.orElseGet()

Learn more about programming Java Optionals.

By 
Vishwa Ratna user avatar
Vishwa Ratna
DZone Core CORE ·
Sep. 30, 19 · Presentation
Likes (15)
Comment
Save
Tweet
Share
26.8K Views

Join the DZone community and get the full member experience.

Join For Free

Programming Java optionals

Learn more about programming Java Optionals

A very common misunderstanding, as well as bad usage, can prevail if you simply go by the dictionary and semantic definition of Optional.orElse() and Optional.orElseGet().

A smart man makes a mistake, learns from it, and never makes that mistake again. But a wise man finds a smart man and learns from him and how to avoid the mistake altogether.

The difference is pretty subtle, and if you don't pay close attention, then you will continue to make the same mistakes.

You may also like: 26 Reasons Why Using Optional Correctly Is Not Optional

The best way to understand the difference between orElse() and orElseGet() is that orElse() will always be executed if the Optional<T> is null or not. But orElseGet() will only be executed when Optional<T> is null.

The dictionary meaning of orElse is: "execute the part when something is not present," but here it contradicts that, as shown in the following example:

    Optional<String> nonEmptyOptional = Optional.of("Vishwa Ratna");
    String value = nonEmptyOptional.orElse(iAmStillExecuted());

    public static String iAmStillExecuted(){
    System.out.println("nonEmptyOptional is not NULL,still I am being executed");
    return "I got executed";
    }


Output: nonEmptyOptional is not NULL, but still, I am executing:

    Optional<String> emptyOptional = Optional.ofNullable(null);
    String value = emptyOptional.orElse(iAmStillExecuted());
    public static String iAmStillExecuted(){
    System.out.println("emptyOptional is NULL, I am being executed, it is normal as 
    per dictionary");
    return "I got executed";
    }


Output: emptyOptional is NULL. I am now executing it as usual, as per its dictionary definition.

For orElseGet(), the method follows its dictionary meaning. The orElseGet() part will be executed only when the Optional is null.

Benchmarks:

+--------------------+------+-----+------------+-------------+-------+
| Benchmark          | Mode | Cnt | Score      | Error       | Units |
+--------------------+------+-----+------------+-------------+-------+
| orElseBenchmark    | avgt | 20  | 60934.425  | ± 15115.599 | ns/op |
+--------------------+------+-----+------------+-------------+-------+
| orElseGetBenchmark | avgt | 20  | 3.798      | ± 0.030     | ns/op |
+--------------------+------+-----+------------+-------------+-------+


Remarks: orElseGet() has clearly outperformed orElse() for our particular example.

Hopefully, this post clears up any doubts from people like me who need a very basic example. Please share your thoughts in the comments.

Further Reading

Java 8 Optional Usage and Best Practices

26 Reasons Why Using Optional Correctly Is Not Optional

Dictionary (software) Java (programming language) POST (HTTP) Clear (Unix) Semantics (computer science)

Published at DZone with permission of Vishwa Ratna. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Create a Stub in 5 Minutes
  • Commonly Occurring Errors in Microsoft Graph Integrations and How to Troubleshoot Them (Part 3)
  • Linked List Popular Problems Vol. 1
  • Coordinating Threads Using CountDownLatch

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook