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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Microservices Decoded: Unraveling the Benefits, Challenges, and Best Practices for APIs
  • An Overview of Kubernetes Security Projects at KubeCon Europe 2023
  • Top 10 Pillars of Zero Trust Networks
  • A Complete Guide to AWS File Handling and How It Is Revolutionizing Cloud Storage

Trending

  • Microservices Decoded: Unraveling the Benefits, Challenges, and Best Practices for APIs
  • An Overview of Kubernetes Security Projects at KubeCon Europe 2023
  • Top 10 Pillars of Zero Trust Networks
  • A Complete Guide to AWS File Handling and How It Is Revolutionizing Cloud Storage
  1. DZone
  2. Coding
  3. Java
  4. Optional.orElse() Vs. Optional.orElseGet()

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

Learn more about programming Java Optionals.

Vishwa Ratna user avatar by
Vishwa Ratna
CORE ·
Sep. 30, 19 · Presentation
Like (11)
Save
Tweet
Share
23.87K 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

A Look at Java Optionals

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.

Trending

  • Microservices Decoded: Unraveling the Benefits, Challenges, and Best Practices for APIs
  • An Overview of Kubernetes Security Projects at KubeCon Europe 2023
  • Top 10 Pillars of Zero Trust Networks
  • A Complete Guide to AWS File Handling and How It Is Revolutionizing Cloud Storage

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: