DEV Community

realNameHidden
realNameHidden

Posted on

1 1 1 1 1

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.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay