Real World Example

Coupon Lookup at Checkout

An e-commerce checkout looks up a coupon code that the user may or may not have typed, checks if it is still valid and applies the discount. Optional keeps the flow readable without nested ifs.

Example

import java.time.LocalDate;
import java.util.*;

public class Main {
    static final LocalDate TODAY = LocalDate.of(2025, 10, 15);
    static final Map<String, Coupon> COUPONS = Map.of(
            "DIWALI20", new Coupon("DIWALI20", 20, LocalDate.of(2025, 11, 5)),
            "SUMMER10", new Coupon("SUMMER10", 10, LocalDate.of(2025, 6, 30)));

    static Optional<Coupon> findValidCoupon(String code) {
        return Optional.ofNullable(code)
                .map(String::trim)
                .map(String::toUpperCase)
                .filter(c -> !c.isEmpty())
                .map(COUPONS::get)
                .filter(c -> !c.expiresOn().isBefore(TODAY));
    }

    public static void main(String[] args) {
        int cart = 2500;
        for (String input : Arrays.asList(" diwali20 ", "SUMMER10", "", null, "FREE100")) {
            int payable = findValidCoupon(input)
                    .map(c -> cart - cart * c.percent() / 100)
                    .orElse(cart);
            System.out.printf("%-12s -> pay Rs %d%n", input, payable);
        }
    }
}

record Coupon(String code, int percent, LocalDate expiresOn) {}

Output

 diwali20    -> pay Rs 2000
SUMMER10     -> pay Rs 2500
             -> pay Rs 2500
null         -> pay Rs 2500
FREE100      -> pay Rs 2500