Logo

dev-resources.site

for different kinds of informations.

How does Optional.ifPresent() differ from Optional.orElse()?

Published at
12/15/2024
Categories
java
interview
streams
questions
Author
realnamehidden1_61
Categories
4 categories in total
java
open
interview
open
streams
open
questions
open
Author
18 person written this
realnamehidden1_61
open
How does Optional.ifPresent() differ from Optional.orElse()?

Optional.ifPresent() and Optional.orElse() are two methods in Java's Optional class, designed to handle optional values gracefully, but they serve different purposes and are used in different scenarios.

1. Optional.ifPresent()

The ifPresent() method executes a given action if a value is present in the Optional. It is typically used for side effects when the value exists.

Key Characteristics:

Action Execution:
Executes the specified consumer only if the Optional contains a value.

No Return Value:
It does not return anything (void method).

Optional<String> optional = Optional.of("Hello");

optional.ifPresent(value -> System.out.println("Value is: " + value));
// Output: Value is: Hello

Optional<String> emptyOptional = Optional.empty();
emptyOptional.ifPresent(value -> System.out.println("Value is: " + value));
// No output since the Optional is empty.

Enter fullscreen mode Exit fullscreen mode

Use Case:

Performing an action (e.g., logging, updating state) if the value exists.
Avoiding explicit null checks before acting on a value.

2. Optional.orElse()

The orElse() method returns the value contained in the Optional, or a default value if the Optional is empty.

Key Characteristics:

Returns a Value:
Always returns a value, either the contained value or the default.
No Side Effects:
Does not execute any action, only returns the value.

Optional<String> optional = Optional.of("Hello");
String value = optional.orElse("Default");
System.out.println(value); // Output: Hello

Optional<String> emptyOptional = Optional.empty();
String emptyValue = emptyOptional.orElse("Default");
System.out.println(emptyValue); // Output: Default

Enter fullscreen mode Exit fullscreen mode

Use Case:

Providing a fallback/default value when the Optional is empty.
Ensuring that a non-null value is always returned from an Optional.

Combining Both in a Scenario

Example:
You have an Optional representing a username. If the username exists, you log it. If it doesn't, you use a default username.

Optional<String> username = Optional.of("JohnDoe");

// Log the username if present
username.ifPresent(name -> System.out.println("User logged in: " + name));

// Get the username or default to "Guest"
String displayName = username.orElse("Guest");
System.out.println("Display name: " + displayName);

// Output:
// User logged in: JohnDoe
// Display name: JohnDoe

Enter fullscreen mode Exit fullscreen mode

Summary
Use ifPresent() when you want to perform an action on the value if it exists.

Use orElse() when you want to retrieve a value, ensuring a default is returned if the Optional is empty.

questions Article's
30 articles in total
Favicon
10 Must-Know Software Testing Interview Questions
Favicon
How does Optional.ifPresent() differ from Optional.orElse()?
Favicon
10 questions developers should ask our self
Favicon
DSA: Array - questions
Favicon
DSA: LinkedList questions
Favicon
DSA: Stack - Questions
Favicon
How to Build an Effective Study Space for IT Certification Preparation: A BCS Business Analysis (BAPv5) Approach
Favicon
Why do I get so many followers on this platform?
Favicon
The Ultimate 2024 Adobe AD0-E555 Exam Question Set for Confident Preparation
Favicon
How to change the redirect URL when changing a user's email in Supabase?
Favicon
Figure out gfg IDLE
Favicon
When "The Best" isn't good enough
Favicon
20 Best Questions to Ask Yourself for Self Growth
Favicon
How to ask better questions?
Favicon
Join Our Organisation
Favicon
How do animation libraries affect SEO in the Next JS?
Favicon
Choosing right tech stack
Favicon
Frontend Fundamentals: Top 10 Interview Questions and In-Depth Answers for Every Developer
Favicon
Top 11 Microprocessor Interview Questions and Answers
Favicon
What should I do?
Favicon
Master Your Success Journey with Pass4success SAP C_S43_2022 Exam Prep
Favicon
Can anyone recommend a modern CSS course?
Favicon
Creating Smart Questions with NestJS and OpenAI
Favicon
111+ Interview Questions - Flutter
Favicon
How to Structure your Resume After your First Job
Favicon
Top 25 Kafka interview questions
Favicon
Top 10 Java interview questions
Favicon
Getting an issue with the (!) mark after the domain name
Favicon
101 questions for python developer
Favicon
google chrome pdf extension

Featured ones: