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
➡️ Returns an Optional
Use case: Chain multiple Optionals gracefully.
💡 orElse(T other)
📦 Return the value if present, or a default value (always evaluated!)
➡️ 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
➡️ Returns the value directly
✅ Safer than orElse() when the fallback is expensive.
🚨 orElseThrow()
💣 Return the value if present, or throw a NoSuchElementException
➡️ Returns the value directly or throws
🔧 orElseThrow(Supplier〈Exception〉)
🧨 Return the value if present, or throw a custom exception
➡️ 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 ?
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!