[英]Java8 optional and null check
我有以下代碼:
final Optional<List<ServiceAttributeValue>> attributeValueList = Optional.<Product> of(product)
.map(Product::getServiceAttributes)
.map(ServiceAttributeMap::getMap)
.map((v) -> (ServiceAttribute) v.get(attributeV.getAttributeString()))
.map((c) -> (List<ServiceAttributeValue>) c.getValueList());
我是否需要添加檢查 v 是否為空?
首先,你的代碼有問題。 您使用 Optional 來避免 NPE,如果產品為空,您的代碼將拋出 NPE。 您應該使用Optional.ofNullable
代替。
Optional.ofNullable(product)
答案是否定的,如果ServiceAttributeMap::getMap
返回 null,則不會執行第三個映射
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.