Optional: Purpose, Usage and Anti-Patterns

Difficulty: Intermediate

Question

What is Optional and why was it introduced? Explain orElse vs orElseGet, map vs flatMap and the common anti-patterns.

Answer

Tony Hoare called the null reference his billion-dollar mistake, and NullPointerException is probably the most common exception in Java. Optional, introduced in Java 8, is an attempt to make the possible absence of a value explicit in the type of a method's return value, so that callers are forced to think about the empty case instead of forgetting a null check.

Optional<T> is a container that either holds a non-null value or is empty. You create one with Optional.of(value) (throws NullPointerException if the value is null), Optional.ofNullable(value) (empty if null) and Optional.empty(). A method like findUserById returning Optional<User> tells the reader in its signature that a user might not exist.

Here is the working vocabulary. isPresent and isEmpty (Java 11) check for a value; but if you find yourself writing if (opt.isPresent()) opt.get(), you have just rewritten a null check with extra steps. Prefer the functional style. map(fn) transforms the value if present and returns an Optional of the result. filter(predicate) keeps the value only if it matches. flatMap(fn) is used when the function itself returns an Optional, to avoid nesting Optional<Optional<T>>. ifPresent(consumer) runs an action; ifPresentOrElse (Java 9) handles both cases. For extracting: orElse(default), orElseGet(supplier), orElseThrow() and orElseThrow(supplier). Java 9 added or(supplier) to chain a fallback Optional and stream() to turn it into a zero-or-one element stream.

The orElse versus orElseGet question is a favourite. orElse(x) evaluates its argument eagerly, always, even when the Optional has a value. If the argument is a method call that hits the database or builds a large object, you pay for it every time and may trigger side effects. orElseGet takes a Supplier that runs only if the Optional is empty. So use orElse for cheap constants and orElseGet for anything expensive. The get method without a check throws NoSuchElementException when empty, so prefer orElseThrow(), which states the intent clearly.

Chained navigation shows the value best. Instead of checking user, then address, then city for null, write Optional.ofNullable(user).map(User::getAddress).map(Address::getCity).orElse("Unknown"). If any link is null, the chain safely yields the default.

Anti-patterns to avoid. Do not use Optional as a field in entities or as a method parameter; it is not Serializable, adds overhead, and overloads or nullable parameters are clearer. It was designed mainly as a return type. Never return null from a method whose return type is Optional. Do not wrap collections; return an empty list rather than Optional<List>. Do not call get without checking. And do not use Optional.of on values that might be null.

For primitives use OptionalInt, OptionalLong and OptionalDouble to avoid boxing, as returned by IntStream.max or average.

Finally, be honest in interviews: Optional does not remove null from Java, and it is just an object with its own allocation cost, so it is not needed in hot inner loops. Its value is documentation and forcing handling at API boundaries.

Code examples

Chaining and orElse vs orElseGet

import java.util.Optional;

public class OptionalDemo {
    static String expensive() {
        System.out.println("computing");
        return "x";
    }

    public static void main(String[] args) {
        String city = Optional.<String>ofNullable(null)
            .map(String::trim)
            .orElse("guest");
        System.out.println(city);

        String r1 = Optional.of("a").orElse(expensive());
        String r2 = Optional.of("a").orElseGet(() -> expensive());
        System.out.println(r1 + " " + r2);

        System.out.println(Optional.of(15).filter(n -> n > 18).isPresent());

        Optional.of("Asha").ifPresentOrElse(
            n -> System.out.println("Hi " + n),
            () -> System.out.println("nobody"));
    }
}

orElse evaluated expensive() even though the Optional had a value, printing computing. orElseGet skipped it. The filter removed 15 because it is not above 18.

Key points

Common follow-up questions

Interview tips

Concepts covered

Optional, NullPointerException, orElse vs orElseGet, map, flatMap

More Core Java & Collections questions