Java8可选和空检查

Java8可选和空检查,java,nullpointerexception,null,java-8,optional,Java,Nullpointerexception,Null,Java 8,Optional,我有以下代码: final Optional<List<ServiceAttributeValue>> attributeValueList = Optional.<Product> of(product) .map(Product::getServiceAttributes) .map(ServiceAttributeMap::getMap) .map((v) -> (ServiceAttribut

我有以下代码:

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());
final Optional attributeValueList=可选。(产品)的
.map(产品::getServiceAttributes)
.map(ServiceAttributeMap::getMap)
.map((v)->(ServiceAttribute)v.get(attributeV.getAttributeString())
.map((c)->(List)c.getValueList());

我需要添加检查v是否为null吗?

首先,您的代码有缺陷。您可以使用Optional来避免NPE,当产品为null时,代码将抛出NPE。您应该改为使用
可选.ofNullable

Optional.ofNullable(product)

答案是否定的,如果
ServiceAttributeMap::getMap
返回null,那么第三个映射将不会执行。您可能不需要
,也不需要单参数lambdas周围的前缀(您可以用
v->
替换
)。为什么您认为他的
产品可以为null?作者并没有这样说。看见