Vivek Goel
Vivek Goel

Reputation: 24150

Java8 optional and null check

I have following code:

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());

do I need to add check if v is null?

Upvotes: 2

Views: 565

Answers (1)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23329

First of all, your code is buggy. You using Optional to avoid NPE where your code will throw NPE if product is null. You should use Optional.ofNullable instead.

Optional.ofNullable(product)

and the answer is no, the third map will not get executed if ServiceAttributeMap::getMap returns null

Upvotes: 2

Related Questions