[英]How to translate a Optional mapping to Stream mapping in Java
我有这个当前的逻辑:
List<String> priceUnitCodes = ofNullable(product.getProductPrices())
.map(ProductPrices::getProductPrices)
.flatMap(productPrices -> productPrices.stream()) // << error highlight
.map(ProductPrice::getPriceBase)
.map(PriceBase::getPriceUnit)
.map(UniversalType::getCode)
.collect(Collectors.toList());
在 IntelliJ 中, flatMap
部分突出显示并显示以下错误提示:
no instance(s) of type variable(s) U exist so that Stream<ProductPrice> conforms to Optional<? extends U>
我知道Optionals
和Stream
是两个不同的东西,但我想知道是否有办法将它们组合起来,这样我就可以在Optional<List<?>>
之后使用Stream
。
由于您从Optional
开始,因此您必须决定当Optional
为空时要返回什么。
一种方法是将Stream
管道放入Optional
的map
内:
List<String> priceUnitCodes = ofNullable(product.getProductPrices())
.map(ProductPrices::getProductPrices)
.map(productPrices -> productPrices.stream()
.map(ProductPrice::getPriceBase)
.map(PriceBase::getPriceUnit)
.map(UniversalType::getCode)
.collect(Collectors.toList())
.orElse(null);
或者当然,如果Stream
管道内的map
操作可能返回null
,则需要进行额外的更改(以避免NullPointerException
)。
另一方面,如果它们永远无法返回null
,则可以将它们链接到单个map
:
List<String> priceUnitCodes = ofNullable(product.getProductPrices())
.map(ProductPrices::getProductPrices)
.map(productPrices -> productPrices.stream()
.map(pp -> pp.getPriceBase().getPriceUnit().getCode())
.collect(Collectors.toList())
.orElse(null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.