如何在Java中将可选映射转换为流映射

我有这个当前逻辑:

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());

我知道flatMapno instance(s) of type variable(s) U exist so that Stream<ProductPrice> conforms to Optional<? extends U> 是两个不同的东西,但是我想知道是否有一种方法可以将它们结合起来,以便我可以将OptionalsStream一起使用之后。

SophiaBJ 回答:如何在Java中将可选映射转换为流映射

由于您是从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
,

如果您使用的是Java 9+,则可以使用Optional.stream,然后使用flatMap

ofNullable(product.getProductPrices())
.map(ProductPrices::getProductPrices)
.stream()
.flatMap(Collection::stream) //assuming getProductPrices returns a Collection
...

Optional.stream如果可选字段为空,则返回空流。

,

另一种解决方案是使用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());
本文链接:https://www.f2er.com/3103250.html

大家都在问