Java8可选和空检查

时间:2015-09-09 20:00:36

标签: java nullpointerexception null java-8 optional

我有以下代码:

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是否为空?

1 个答案:

答案 0 :(得分:2)

首先,您的代码是错误的。您使用Optional来避免NPE,如果product为null,您的代码将抛出NPE。您应该使用Optional.ofNullable代替。

Optional.ofNullable(product)

并且答案是否定的,如果ServiceAttributeMap::getMap返回null

,则不会执行第三个映射