Convert Optional to boolean in functional style

Viewed 8123

I just wanted to return a boolean from an Optional object by doing a check on the getProductType() on the ProductDetails object as shown below:

public boolean isElectronicProduct(String productName) {
    Optional<ProductDetails> optProductDetails = findProductDetails(productName);
    if(optProductDetails.isPresent()) {
        return optProductDetails.get().getProductType() == ProductType.ELECTRONICS;
    }
    return false;
}

Intellij complains stating that the above code can be replaced in functional style, is there really any way to simplify the above Optional object and return a boolean?

3 Answers

Change this:

if(optProductDetails.isPresent()) {
    return optProductDetails.get().getProductType() == ProductType.ELECTRONICS;
}
return false;

To:

return optProductDetails
      .filter(prodDet -> prodDet.getProductType() == ProductType.ELECTRONICS)  // Optional<ProductDetails> which match the criteria
      .isPresent();   // boolean

You can read more about functional-style operations on Optional values at: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

This is what you need:

return findProductDetails(productName)
    .map(ProductDetails::getProductType)
    .map(ProductType.ELECTRONICS::equals)
    .orElse(false);

I prefer to split things out with the extra map call, rather than calling productDetails.getProductType() directly before the comparison. I think it's just slightly easier to read.

optProductDetails.map(d -> d.getProductType() == ProductType.ELECTRONICS) //Optional<Boolean>
                 .orElse(false); //Boolean
Related