I am trying to understand and use Java 8 - Optional feature. I would like to refactor this code block. Without Optional I have such a condition.
ClassA objA = findObject();
if(objA == null || objA.isDeleted()){
throw Exception("Object is not found.");
}
I want to transform this block using Optional wrapper. I have read about filter, ifPresent functions but I could not find a way. Maybe it is simple but I am new to Java 8. I would appreciate if you could help.
You shouldn't use Optional<T>
to solely replace the if
statement as it's no better and doesn't gain you any benefit. A much better solution would be to make the findObject()
method return Optional<ClassA>
.
This makes the caller of this method decide what to do in the "no value" case.
Assuming you've made this change, you can then leverage the Optional<T>
type:
findObject().filter(a -> !a.isDeleted()) // if not deleted then do something
.map(...) // do some mapping maybe?
... // do some additional logic
.orElseThrow(() -> new Exception("Object is not found."));//if object not found then throw exception
see the Optional<T>
class to familiarise your self with the API and the methods that are available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With