How to work correctly with Optional if I need to complete a method (with some actions, log for example) in case of an empty Optional? Otherwise, get the object from Optional and continue working
I found similar problem https://stackoverflow.com/a/55393419/1460643 But there return is used in lambda
My code,
...
var productOptional = productVersionMongoService.findById(crmProductId)
.map(ProductVersion::getProductId)
.flatMap(productMongoService::findById);
Product product;
if (productOptional.isEmpty()) {
log.warn(...);
return Collections.emptySet();
} else {
product = productOptional.get();
}
...
So my question is, is it possible to refactor it to make the code more attractive?
I would write it like this, although it isn't completely clear from your question what gets returned in the case that a
Productis found.: