← All articles
Backend1 min read

Working with Optional in Java

Optional was meant to end the null-check ritual, but misused it just moves the problem. Here is how to use it the way it was designed.

S

Swapnika Voora

Author

Optional expresses "a value might be absent" in the type system. Used well it removes defensive null checks; used poorly it adds ceremony without safety.

Transform, don't unwrap early

Chain map and filter so the absent case flows through untouched. Calling get() early throws away everything the type gave you.

UserService.java
return repository.findById(id)
    .map(User::getEmail)
    .filter(email -> email.endsWith("@corp.com"))
    .orElseThrow(() -> new AccessDenied(id));

Return it, don't store it

Optional is a return type for methods that may find nothing. It is not meant for fields or method parameters.

Repo.java
Optional<User> findById(String id);   // good
// private Optional<String> name;     // avoid as a field

Takeaways

  • Never call get() without checking isPresent() — use orElse or orElseThrow.
  • Do not use Optional for collections; return an empty list instead.
  • Prefer orElseGet over orElse when the fallback is expensive to compute.

Treat Optional.of(null) as a bug — it throws immediately. Use ofNullable when the value may legitimately be null.

#java#optional#best-practices

More in Backend