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

Anti-Pattern: Using Optional for Collections

Why returning Optional<List<T>> is redundant when empty collections already express absence.

Anti-Pattern: Using Optional for Collections

You'll learn why wrapping collections in Optional creates unnecessary complexity when empty collections already express absence.

The Redundancy Problem

When you have a method that returns a collection (like List<T>, Set<T>, or Map<K,V>), you might be tempted to return Optional<List<T>> to handle the "no results" case. However, this is redundant because collections already have a perfectly good way to represent absence: an empty collection.

An empty List is not the same as null—it's a valid, safe object that clearly means "no items." Wrapping it in Optional creates a double-layer of "emptiness" that confuses callers.

Why It's an Anti-Pattern

// ANTI-PATTERN: Unnecessary Optional wrapper
public Optional<List<User>> findUsers(String criteria) {
    List<User> results = database.query(criteria);
    return results.isEmpty() 
        ? Optional.empty() 
        : Optional.of(results);
}

// BETTER: Return empty collection directly
public List<User> findUsers(String criteria) {
    List<User> results = database.query(criteria);
    return results; // Returns empty list if no matches
}

The anti-pattern forces callers to unwrap the Optional and then check if the collection is empty—two steps where one suffices. Collections are designed to be safe when empty; they support iteration, stream operations, and size checks without throwing exceptions.

The Right Mental Model

Think of an empty collection like an empty container: it's still a container, just with nothing inside. You don't need to wrap the entire container in another box labeled "might not exist." The empty state is the container's natural way of saying "I have nothing for you."

Key Takeaway:
Always return an empty collection instead of Optional<Collection>—empty collections are self-documenting, safe to use, and avoid unnecessary wrapper overhead.