Articles Java

Java Optional best practices: 7 common mistakes

The Java Optional best practices fit in one sentence: use Optional only as the return type of a method that may have no result, never call get() on it, and let map, orElse, orElseGet, orElseThrow and ifPresent handle the empty case for you. Most common mistakes with Optional break one of those three rules. Below are seven of them, each with the code people write and the code to write instead. Everything here behaves the same on Java 21 and Java 25.

What is Optional for in Java?

Optional<T> is a small container that holds either one non-null value or nothing. Its Javadoc states the purpose in an API note: it is “primarily intended for use as a method return type where there is a clear need to represent ‘no result’”, and where returning null is likely to cause errors.

Optional<User> findById(long id) {
    return Optional.ofNullable(users.get(id));
}

The signature now tells the caller that a user may be missing, and the compiler will not let them treat the result as a User until they decide what happens in that case. That is the whole feature. Optional is not a general replacement for null, and the mistakes below mostly come from treating it as one.

Mistake 1: calling get() without a check

User user = findById(id).get();

When the user does not exist, this throws NoSuchElementException: No value present. You replaced a NullPointerException with a different exception and gained nothing.

If a missing value really is a bug at this point in the code, say so with orElseThrow(). Even better, throw an exception that explains what was missing:

User user = findById(id).orElseThrow();

User user = findById(id)
        .orElseThrow(() -> new IllegalArgumentException("No user with id " + id));

The no-argument orElseThrow() exists since Java 10 and does exactly what get() does. The Javadoc of get() calls it “the preferred alternative”, because its name admits that it can throw. Treat every get() in a code review as a question: what happens when this is empty?

Mistake 2: isPresent() followed by get()

Optional<User> user = findById(id);
String email;
if (user.isPresent()) {
    email = user.get().email().toLowerCase();
} else {
    email = "unknown";
}

This is correct, but it is a null check with more typing. Optional already knows how to run code only when a value is present:

String email = findById(id)
        .map(User::email)
        .map(String::toLowerCase)
        .orElse("unknown");

map transforms the value if there is one and passes an empty Optional through untouched. It also returns an empty Optional when the function returns null, so a chain of map calls is safe on nullable getters. For side effects, use ifPresent, or ifPresentOrElse (Java 9 and later) when the empty case needs handling too:

findById(id).ifPresent(user -> System.out.println("Found " + user.email()));

findById(id).ifPresentOrElse(
        user -> System.out.println("Found " + user.email()),
        () -> System.out.println("No user with id " + id));

isPresent() and isEmpty() (Java 11 and later) are fine when a boolean is all you need. The smell is the pair: isPresent() and then get().

Mistake 3: orElse when you need orElseGet

orElse(value) and orElseGet(supplier) look interchangeable. They are not. The argument of orElse is an ordinary method argument, so Java evaluates it before orElse runs, whether the Optional is empty or not. This program shows it:

import java.util.Optional;

public class OrElseDemo {

    static String loadDefault() {
        System.out.println("  loadDefault() called");
        return "guest";
    }

    public static void main(String[] args) {
        Optional<String> name = Optional.of("anna");

        System.out.println("orElse:");
        String a = name.orElse(loadDefault());
        System.out.println("  result = " + a);

        System.out.println("orElseGet:");
        String b = name.orElseGet(() -> loadDefault());
        System.out.println("  result = " + b);
    }
}

Output on JDK 25:

orElse:
  loadDefault() called
  result = anna
orElseGet:
  result = anna

The value was present both times, yet orElse still called loadDefault() and threw the result away. If that method queries a database, calls another service or creates a record, you pay for it on every call, and a side effect happens when it should not.

The rule: orElse for a constant or a value you already have, orElseGet for anything that has to be computed. The same applies when the fallback is another Optional: use or(() -> ...), added in Java 9, which also takes a supplier.

Mistake 4: Optional as a field or a method parameter

class Customer {
    private Optional<String> phone;

    public void setPhone(Optional<String> phone) {
        this.phone = phone;
    }
}

Three things go wrong here. The field can still be null, so now there are three states to handle instead of two. Every caller has to wrap its argument: setPhone(Optional.of(number)). And Optional does not implement Serializable, which breaks classes that rely on Java serialization.

Keep the field a plain nullable reference and expose Optional only where the value leaves the class:

class Customer {
    private String phone; // may be null

    public Optional<String> phone() {
        return Optional.ofNullable(phone);
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

For optional parameters, overloading reads better at the call site. Compare search(query, Optional.empty()) with search(query):

List<User> search(String query) {
    return search(query, 50);
}

List<User> search(String query, int limit) { ... }

Mistake 5: wrapping a collection in Optional

Optional<List<Order>> findOrders(long customerId) {
    List<Order> found = orders.stream()
            .filter(order -> order.customerId() == customerId)
            .toList();
    return found.isEmpty() ? Optional.empty() : Optional.of(found);
}

A collection already has a way to say “nothing”: it is empty. Wrapping it forces the caller to unwrap first and then loop, and leaves them wondering whether an empty Optional and a present empty list mean different things. Return the list:

List<Order> findOrders(long customerId) {
    return orders.stream()
            .filter(order -> order.customerId() == customerId)
            .toList();
}

A for loop over the result simply does nothing when there are no orders. The same goes for arrays, maps and streams.

Mistake 6: returning null from a method that declares Optional

Optional<User> findByEmail(String email) {
    if (email == null) {
        return null;
    }
    return users.values().stream()
            .filter(user -> user.email().equals(email))
            .findFirst();
}

This compiles, because Optional is a normal reference type. The caller trusts the signature, writes findByEmail(email).isPresent() and gets a NullPointerException from the one type that was supposed to prevent it. The API note is blunt about it: a variable of type Optional “should never itself be null”. Return Optional.empty():

if (email == null) {
    return Optional.empty();
}

Mistake 7: Optional.of when the value can be null

Optional<String> setting(String key) {
    return Optional.of(settings.get(key));
}

Optional.of requires a non-null argument and throws NullPointerException otherwise. A map lookup returns null for a missing key, so this method fails in exactly the case it was written for. Use ofNullable, which turns null into an empty Optional:

return Optional.ofNullable(settings.get(key));

Both have their place. Optional.of(value) is right when the value cannot be null, and failing fast there is a feature. Optional.ofNullable(value) is for values that come from code that may return null.

What about OptionalInt, OptionalLong and OptionalDouble?

They are the primitive versions, returned for example by IntStream.max(), and they avoid boxing an int into an Integer. You read the value with getAsInt(), orElse(0) or orElseThrow(). They have no map, filter or flatMap, so they are best as the end of a stream pipeline rather than something you pass around.

Java Optional best practices in short

  • Return Optional from a method that may have no result. Do not use it for fields or parameters.
  • Never return null from a method that declares Optional. Return Optional.empty().
  • Do not call get(). Use orElseThrow(), ideally with your own exception.
  • Replace isPresent() plus get() with map, orElse, ifPresent or ifPresentOrElse.
  • orElse for a value you already have, orElseGet for one that must be computed.
  • Return an empty collection instead of an Optional of a collection.
  • Optional.of for values that are never null, Optional.ofNullable for the rest.
  • For primitives coming out of streams, expect OptionalInt, OptionalLong and OptionalDouble.