[VV122] The Java 21 Newsletter: 🔍 Mastering Java's Optional or/get Methods – Once and for All!
[VV122] The Java 21 Newsletter: 🔍 Mastering Java's Optional or/get Methods – Once and for All!
Working with Java's Optional is great... until you mix up all the or, orElse, and orElseThrow methods 😵💫
Let's clear the confusion with a simple breakdown of what each method really does 👇
✅ When you have an Optional〈T〉…
⚙️ or(Supplier〈Optional〈T〉〉 supplier)
🔁 Used to chain another optional only if the current one is empty
optional.or(() -> Optional.of("fallback"))➡️ Returns an Optional
Use case: Chain multiple Optionals gracefully.
💡 orElse(T other)
📦 Return the value if present, or a default value (always evaluated!)
optional.orElse("fallback")➡️ Returns the value directly
❗ Beware: other is evaluated even if not used!
🧠 orElseGet(Supplier〈T〉 supplier)
🛠 Return the value if present, or lazily compute a fallback
optional.orElseGet(() -> computeValue())
➡️ Returns the value directly
✅ Safer than orElse() when the fallback is expensive.
🚨 orElseThrow()
💣 Return the value if present, or throw a NoSuchElementException
optional.orElseThrow()
➡️ Returns the value directly or throws
🔧 orElseThrow(Supplier〈Exception〉)
🧨 Return the value if present, or throw a custom exception
optional.orElseThrow(() -> new MyException("No value!"))
➡️ Returns the value directly or throws
🧠 TL;DR Cheat Sheet

🧩 Bonus Tip
When in doubt, ask yourself:
Do I want to supply another optional, a direct fallback, a lazy fallback, or throw an exception ?
Do I want to supply another optional, a direct fallback, a lazy fallback, or throw an exception ?
This clarity makes the API feel intuitive 🧘♂️
🏷 #JavaTips #Optional #CleanCode #JavaDevelopers #CodeBetter #Java #SoftwareCraftsmanship #OptionalExplained #DeveloperMindset #FunctionalProgramming
🔁 Feel free to save & share with anyone confused by Optional methods!