在功能样式中将Optional转换为boolean

dev*_*per 6 java optional java-8

我只是想返回booleanOptional做在检查对象getProductType()上的ProductDetails对象,如下图所示:

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

Intellij抱怨说上面的代码可以在功能样式中替换,有没有办法简化上面的Optional对象并返回一个boolean

lea*_*iro 7

改变这个:

if(optProductDetails.isPresent()) {
    return optProductDetails.get().getProductType() == ProductType.ELECTRONICS;
}
return false;
Run Code Online (Sandbox Code Playgroud)

:

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

您可以Optional在以下网址阅读有关值的功能样式操作的更多信息:https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html


Joe*_*e C 5

optProductDetails.map(d -> d.getProductType() == ProductType.ELECTRONICS) //Optional<Boolean>
                 .orElse(false); //Boolean
Run Code Online (Sandbox Code Playgroud)


Mic*_*ael 5

这就是你需要的:

return findProductDetails(productName)
    .map(ProductDetails::getProductType)
    .map(ProductType.ELECTRONICS::equals)
    .orElse(false);
Run Code Online (Sandbox Code Playgroud)

我更喜欢用额外的map调用来解决问题,而不是productDetails.getProductType()在比较之前直接调用.我认为这只是稍微容易阅读.