簡體   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