What is the recommended way to use Optional<T>?
Options
- Call
optional.get()directly each time you need a value - Return type for 'maybe absent', with
orElseormap(Correct option) - Use it for each field and each method parameter, always
- Use it as a way to make a class thread-safe in Java
Answer
Use it as a return type for "might be absent", and use orElse, orElseThrow, map instead of get() without checking
Why
Optional<T> is a box that may or may not contain a value. It makes "this can be missing" visible in the method signature, instead of returning null and hoping callers remember to check.
Good use: repo.findById(id).map(User::getName).orElse("unknown") or .orElseThrow().
Bad use: calling .get() without checking (it throws if empty), or using Optional for fields and parameters.
Remember
Optional is for return values; avoid bare get().