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