ExampleDifficulty: Intermediate1 min

Optional Example: A Lookup Before and After

The same lookup returning null and returning an Optional, with the same call site in both.

Rewriting a lookup that returns null so that it returns Optional removes the null check from every caller. The same lookup, first returning null:

java
Customer findByReference(String ref) {
    return byRef.get(ref);
}

Customer c = findByReference(ref);
String label = c.name().toUpperCase();
line 6 throws when nothing was found, and nothing in the code suggests it might

And returning an Optional:

java
Optional<Customer> findByReference(String ref) {
    return Optional.ofNullable(byRef.get(ref));
}

String label = findByReference(ref)
        .map(Customer::name)
        .map(String::toUpperCase)
        .orElse("UNKNOWN");

map here is the method on Optional, not the stream operation with the same name, and it follows the same rule: apply the function to the value if there is one, and pass the emptiness along if there is not.

Optional.ofNullable wraps a value that might be null. map applies a function only when there is a value, so both map calls are skipped when the lookup found nothing, and orElse supplies the answer.

No if and no null check, and no way to reach toUpperCase on nothing. The absence is handled once, at the end, rather than at every step.