首页 > 解决方案 > 以函数式风格将 Optional 转换为布尔值

问题描述

我只是想通过对对象进行检查来从对象返回 a ,如下boolean所示:OptionalgetProductType()ProductDetails

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

Intellij 抱怨说上面的代码可以用函数样式替换,真的有什么方法可以简化上面的Optional对象并返回 aboolean吗?

标签: javajava-8optional

解决方案


改变这个:

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

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

您可以在以下位置阅读有关Optional值的函数式操作的更多信息:https ://docs.oracle.com/javase/8/docs/api/java/util/Optional.html


推荐阅读