No, you don't have to.
In theory, Optional<>
s can be null but shouldn't be as the empty value would make more sense.
Returning a null
Optional<>
value is just bad API design.
Spring JPA uses Optional
instead of null
, just like it should do so you can skip the additional null check.
Also, using Optional#ifPresent
indicates that you are using Optional
incorrectly. You may want to use the other methods of Optional
instead.
If you need to execute something if the Optional has a value, you can use the method Optional#ifPresent
:
someOptional.ifPresent(value->doSomething(value));
This might not seem like a big advantage but it works well with other methods like Optional#map:
someOptional.map(value->value.getSomething()).ifPresent(value->doSomething(value))
Optional#map
transforms the object in the Optional
using the passed lambda expression.
Optional#filter
replaces tte object in the Optional
with null
(empty Optional
) if the object doesn't match the passed condition.