DEV Community

realNameHidden
realNameHidden

Posted on

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.

Top comments (0)