'optional.get()' without 'isPresent()' check
Use orElseThrow
as a shortcut. It fetches the value if it exists, otherwise throws an exception, making it obvious when an Optional is unwantedly absent.
Avoid using orElse(null)
without a good reason. It reintroduces null
checks, which Optional
aims to supersede.
Making the most of Optional
When Optional is empty, handle it with style
Optional
is not just a fancier "null". It offers semblances of control over absent values:
orElseThrow()
: Convert absence into an exception.ifPresent()
: Perform an action if the value is available.orElseGet()
: Call a Supplier to provide an alternative when needed.
Better transformations with map
Use map()
to transform an Optional
's value with a Function, elegantly providing an alternative for emptiness.
Conditional logic via filter
To conditionally exclude values based on a Predicate, use filter()
.
Harnessing Optional
in Stream operations
Don't misuse findFirst()
:
Handle the Optional
produced by findFirst()
to provide a default value or allow further operations.
Tips for Unwrapping Optional
Using orElse
for default values
Use orElse
to specify an alternative value when an Optional
is empty.
When to use orElseGet
A more sophisticated option, orElseGet()
uses a Supplier function and only calls it when necessary - a perfect example of lazy evaluation.
Avoiding blunders while unwrapping
Optional
respects the saying - "look before you leap". Use orElseThrow()
instead of get()
to avoid a surprising NoSuchElementException
.
Be Good and Return Optional
Forwarding Optional
to caller
You don’t always have to unwrap Optional
:
Let the caller take charge of the Optional
.
Optional
and Stream
: True Friendship
Optional
can complement Stream
perfectly, allowing nuanced treatment of nullable values in sequences.
Was this article helpful?