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
Newsletter
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

  • Why Your Test Automation Is Always Behind the Code And the Architecture That Fixes It
  • Introducing senro: A Pipeline Engine You Program in Go
  • Spring AI on Local LLMs
  • The Real Cost of Change in Software Development

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
DZone Core CORE ·
Sep. 30, 19 · Presentation
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
27.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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