Difference Between ifPresent() and ifPresentOrElse() in Optional

Both methods belong to the Optional<T> class and are used to handle optional values in Java.

ifPresent() (Java 8)

  • Executes a provided action only if the Optional contains a value.
  • Does nothing if the Optional is empty.

Example: Using ifPresent()

import java.util.Optional;

public class IfPresentExample {
    public static void main(String[] args) {
        Optional optionalValue = Optional.of("Java 8");

        optionalValue.ifPresent(value -> System.out.println("Value: " + value));
    }
}

Output:

Value: Java 8

If the value is present, it prints it; otherwise, it does nothing.

ifPresentOrElse() (Java 9)

  • Executes a provided action if the Optional contains a value.
  • Executes a different action if the Optional is empty.

Example: Using ifPresentOrElse()

import java.util.Optional;

public class IfPresentOrElseExample {
    public static void main(String[] args) {
        Optional optionalValue = Optional.of("Java 9");

        optionalValue.ifPresentOrElse(
            value -> System.out.println("Value: " + value), 
            () -> System.out.println("No value present")
        );

        Optional emptyOptional = Optional.empty();

        emptyOptional.ifPresentOrElse(
            value -> System.out.println("Value: " + value), 
            () -> System.out.println("No value present")
        );
    }
}

Output:

Value: Java 9
No value present

Executes the first lambda if present, otherwise runs the second lambda.

Key Differences

FeatureifPresent() (Java 8)ifPresentOrElse() (Java 9)
When ExecutedIf value is presentIf value is present OR absent
Empty OptionalDoes nothingExecutes a separate action
ArgumentsOne (Consumer)Two (Consumer, Runnable)
Default ActionNot supportedSupported

When to Use What?

  • Use ifPresent() → When you only care about the presence of a value.
  • Use ifPresentOrElse() → When you want to handle both presence and absence.

Example: Handling Database Lookup

import java.util.Optional;

public class UserService {
    public static void main(String[] args) {
        Optional user = findUserById(1);

        user.ifPresentOrElse(
            name -> System.out.println("User found: " + name),
            () -> System.out.println("User not found")
        );
    }

    public static Optional findUserById(int id) {
        return id == 1 ? Optional.of("John Doe") : Optional.empty();
    }
}

Output (if user exists):

User found: John Doe

Output (if user doesn’t exist):

User not found

Best for handling database lookups, APIs, and missing values gracefully.

Summary

  • ifPresent()Performs an action if the value exists, does nothing otherwise.
  • ifPresentOrElse()Handles both cases: executes an action if present, a fallback if absent.
  • ifPresentOrElse() is more flexible but requires Java 9+.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *