QuickDevGuide

Home › Java

Optional — Java

Optional<T> is a container that may or may not hold a value. It makes "no result" explicit in a method's return type instead of returning null. Creating Optional.of(value) (non-null), Optional.ofNullable(maybeNull), Optional.empty(). Consuming — prefer functional style Method Use map / flatMap / filter Transform without null checks orElse(default) Fallback value (always evaluated) orElseGet(() -> …) Lazy fallback (evaluated only if empty) orElseThrow() Throw NoSuchElementException or a custom exception ifPresent / ifPresentOrElse Side effects stream() 0 or 1 element stream (Java 9+) Guidelines ✅ Use as a return type for "might not find it" methods (findById). ❌ Do not use for fields, method parameters or collections (return an empty list instead). ❌ Avoid isPresent() + get() pairs — that…

Key Takeaways