繁体   English   中英

如何将可选映射转换为 Java 中的 Stream 映射

[英]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>

我知道OptionalsStream是两个不同的东西,但我想知道是否有办法将它们组合起来,这样我就可以在Optional<List<?>>之后使用Stream

由于您从Optional开始,因此您必须决定当Optional为空时要返回什么。

一种方法是将Stream管道放入Optionalmap内:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM