I have a optional method which returns Cat
object (which is a optional). From the place I call It i would like to handle it in a way if cat is present then return otherwise continue
Opitional<Cat> option = isCatFound();
if (option.isPresent()) {
return option.get();
}
//DO STUFF HERE IF NO CAT FOUND
The above code is what I have now. I like to use something better than that, a single line solution.
Is there such possibility ? or correct way to use Optional ?
Optional<String> value = Optional. of(str[ 2 ]); // It returns value of an Optional.
Once you have created an Optional object, you can use the isPresent() method to check if it contains a non-null value. If it does, you can use the get() method to retrieve the value. Developers can also use the getOrElse() method, which will return the value if it is present, or a default value if it is not.
Retrieving the value using get() method Optional's get() method returns a value if it is present, otherwise it throws NoSuchElementException. You should avoid using get() method on your Optionals without first checking whether a value is present or not, because it throws an exception if the value is absent.
The Optional
class provides a method for exactly that purpose: orElseGet(Supplier)
. So, with some little helper method you can do this:
Optional<Cat> option = isCatFound();
return option.orElseGet(this::noCatFound);
private Cat noCatFound() {
// do whatever is appropriate here
return null;
}
Of course, you could move the helper method's body into a lambda exprssion that feeds the orElseGet
method.
Since your method has to return a value of that type at the end, you could use
Optional<Cat> option = isCatFound();
return option.orElseGet(() -> {
// DO STUFF HERE IF NO CAT FOUND
// WHICH WILL EVENTUALLY RETURN A VALUE
};
If your “stuff if no cat found” fits into a single line, it might be an option. Otherwise I don’t see any advantage over your original code. Especially as it has the disadvantage that the alternative code path can’t throw checked exceptions any more.
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