How do I conditionally execute code with Optional’s ifPresent and ifPresentOrElse?

In Java, the Optional class provides methods for handling values that may or may not be present. The methods ifPresent and ifPresentOrElse are particularly useful for executing code conditionally based on whether a value is present in the Optional.

1. Using ifPresent

The ifPresent method executes a Consumer when the value is present (i.e., it’s not null). If the Optional is empty, it does nothing. This is useful when you only want to handle the presence of a value and don’t need any fallback action when the value is absent.

Example:

package org.kodejava.util;

import java.util.Optional;

public class OptionalIfPresentExample {
    public static void main(String[] args) {
        // Create an Optional with a value
        Optional<String> optionalValue = Optional.of("Hello, Optional!");

        // Execute only if a value is present
        optionalValue.ifPresent(value -> System.out.println("Value is: " + value));

        // Create an empty Optional
        Optional<String> emptyOptional = Optional.empty();

        // Nothing happens here
        emptyOptional.ifPresent(value -> System.out.println("This won't be printed."));
    }
}

Output:

Value is: Hello, Optional!

2. Using ifPresentOrElse

The ifPresentOrElse method executes a Consumer if the value is present, and executes a Runnable if the value is absent. This is helpful if you want to handle both cases (presence and absence) explicitly.

Example:

package org.kodejava.util;

import java.util.Optional;

public class OptionalIfPresentOrElseExample {
    public static void main(String[] args) {
        // Create an Optional with a value
        Optional<String> optionalValue = Optional.of("Hello, Optional!");

        // Execute the consumer if the value is present, otherwise execute the runnable
        optionalValue.ifPresentOrElse(
                value -> System.out.println("Value is: " + value),
                () -> System.out.println("Value is not present")
        );

        // Create an empty Optional
        Optional<String> emptyOptional = Optional.empty();

        // Handle the absence of value
        emptyOptional.ifPresentOrElse(
                value -> System.out.println("This won't be printed."),
                () -> System.out.println("Value is not present")
        );
    }
}

Output:

Value is: Hello, Optional!
Value is not present

Key Differences:

  1. ifPresent: Only executes when the value is present. It doesn’t account for the absent case.
  2. ifPresentOrElse: Handles both the presence and absence cases, allowing you to define fallback behavior when the value is missing.

Use case:

  • Use ifPresent when you only care about taking action if the value is present.
  • Use ifPresentOrElse when you also want to explicitly perform some alternate action if the value is absent.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.