Course contentsShow
← Java
Lesson 1796 of 2,87037. Optional for Null SafetyFree lesson

Practical ifPresentOrElse Examples: Logging and Defaults

Apply ifPresentOrElse to real scenarios like logging results or executing fallback actions.

Practical ifPresentOrElse Examples: Logging and Defaults

You'll learn how to apply ifPresentOrElse to real-world scenarios like logging operation results and executing fallback behavior.

Real-World Scenarios

While ifPresentOrElse might seem like just another Optional method, it shines in everyday coding situations where you need to handle both success and absence cases with side effects.

Logging Search Results

Imagine searching for a user and logging the outcome:

Optional<User> userOpt = findUserById(123);

userOpt.ifPresentOrElse(
    user -> logger.info("User found: " + user.getName()),
    () -> logger.warn("User ID 123 not found in database")
);

This reads like plain English: "If present, log the user's name; otherwise, log a warning." No if statements, no temporary variables, just clear intent.

Executing Fallback Actions

Consider processing a configuration value with a default action:

Optional<String> configValue = getConfig("max.connections");

configValue.ifPresentOrElse(
    value -> applyConnectionLimit(Integer.parseInt(value)),
    () -> applyConnectionLimit(DEFAULT_CONNECTIONS)
);

Both paths execute actions (side effects), making ifPresentOrElse perfect for this scenario.

Updating UI or State

In application code, you often need to update state based on presence:

Optional<Product> productOpt = inventory.findProduct(sku);

productOpt.ifPresentOrElse(
    product -> displayProduct(product),
    () -> showErrorMessage("Product not available")
);

Why This Pattern Works

ifPresentOrElse excels when you need to perform actions rather than extract values. The Consumer and Runnable parameters make your intent explicit: these are side effects, not transformations.

Key Takeaway: Use ifPresentOrElse for real-world scenarios requiring side effects—like logging results, updating UI state, or executing fallback actions—where both presence and absence need explicit handling.