java - 以函数式风格将 Optional 转换为布尔值
问题描述
我只是想通过对对象进行检查来从对象返回 a ,如下boolean
所示:Optional
getProductType()
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
吗?
解决方案
改变这个:
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
推荐阅读
- arrays - How can we check the content of two different arrays and fetch the corresponding index value from the third array and sum up them?
- hyperledger-fabric - Error while creating and joining a channel on Fabric "Build your first network tutorial"
- python - 从 Python 中的数组初始化实例列表
- android - Android Studio Firebase 依赖与 appcompat 不兼容
- express - 每次我注册一个新用户时,jwt 有效负载都是相同的
- cakephp - CakePHP URL 重定向
- import - 如何导入 seedSuperpixel 模块?
- javascript - 断言已排序的对象数组
- angular - 谷歌时间线图表错误
- python - 如何使用机器学习算法来预测讨论最多的高音扬声器类别