我有这个当前逻辑:
string
在IntelliJ中empty
部分突出显示并显示以下错误提示:
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());
我知道flatMap
和no instance(s) of type variable(s) U exist so that Stream<ProductPrice> conforms to Optional<? extends U>
是两个不同的东西,但是我想知道是否有一种方法可以将它们结合起来,以便我可以将Optionals
与Stream
一起使用之后。
答案 0 :(得分:2)
由于您是从Optional
开始的,因此您必须决定在Optional
为空时返回什么。
一种方法是将Stream
管道放入Optional
的{{1}}中:
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);
管道内的map
操作可能返回Stream
,则将需要进行其他更改(以避免null
)。
另一方面,如果它们再也无法返回NullPointerException
,则可以将它们链接成一个null
:
map
答案 1 :(得分:2)
如果您使用的是Java 9+,则可以使用Optional.stream
,然后使用flatMap
:
ofNullable(product.getProductPrices())
.map(ProductPrices::getProductPrices)
.stream()
.flatMap(Collection::stream) //assuming getProductPrices returns a Collection
...
Optional.stream
如果可选字段为空,则返回空流。
答案 2 :(得分:1)
另一种解决方案是使用Optional
获取orElse
的值,而无需升级到Java-9即可完成。看起来像:
List<String> priceUnitCodes = Optional.ofNullable(product.getProductPrices())
.map(ProductPrices::getProductPrices)
.orElse(Collections.emptyList()) // get the value from Optional
.stream()
.map(ProductPrice::getPriceBase)
.map(PriceBase::getPriceUnit)
.map(UniversalType::getCode)
.collect(Collectors.toList());