Java Optional ifPresentOrElse()

In this guide, you will learn about the Optional ifPresentOrElse() method in Java programming and how to use it with an example.

1. Optional ifPresentOrElse() Method Overview

Definition:

The ifPresentOrElse() method of the Optional class in Java performs a given action if the value is present; otherwise, performs a different action or method. This method is useful for handling both present and absent cases without using explicit isPresent() checks.

Syntax:

public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)

Parameters:

- action: The action to be performed if the value is present.

- emptyAction: The action to be performed if the value is not present.

Key Points:

- It was introduced in Java 9.

- This method does not return a new Optional; it is a terminal operation.

- It takes two parameters, a Consumer to operate on the value inside Optional if it is present, and a Runnable to execute if the Optional is empty.

2. Optional ifPresentOrElse() Method Example

import java.util.Optional;

public class OptionalIfPresentOrElseExample {

    public static void main(String[] args) {

        // Creating an Optional object with a value
        Optional<String> valuePresent = Optional.of("Hello World!");

        // Using ifPresentOrElse() when value is present
        valuePresent.ifPresentOrElse(
                v -> System.out.println("Value is present, it's: " + v),
                () -> System.out.println("Value is absent!")
        );

        // Creating an empty Optional object
        Optional<String> valueAbsent = Optional.empty();

        // Using ifPresentOrElse() when value is absent
        valueAbsent.ifPresentOrElse(
                v -> System.out.println("Value is present, it's: " + v),
                () -> System.out.println("Value is absent!")
        );
    }
}

Output:

Value is present, it's: Hello World!
Value is absent!

Explanation:

In the example, we have two Optional objects – valuePresent which holds a String value, and valueAbsent which is empty. 

We use ifPresentOrElse() on both objects. For valuePresent, the lambda expression in the Consumer parameter is executed, printing the present value. For valueAbsent, the Runnable lambda expression is executed, indicating that the value is absent. This showcases how ifPresentOrElse() can handle both cases elegantly.

Comments