Reputation: 7021
I m trying to use Optional.ofNullable on an a getter that is throwing a NullPointerException :
My code is as follow :
Individual individual = null;
Optional.ofNullable(individual.getIndividualName());
Throwing a NullPointerException here is normal since individual is null
I want to find a pretty way to avoid this exception and get null as result of
Optional.ofNullable(individual.getIndividualName());
The solution in Null check chain vs catching NullPointerException is very heavy. I try it in a jUnit test and takes several seconds to get the result!
Upvotes: 5
Views: 12655
Reputation: 17890
The variable individual
is null and hence the exception.
You should rather have
Optional.ofNullable(individual)
map(Individual::getIndividualName);
The above returns Optional<Type>
where Type
is the return type of getIndividualName()
The solution in Null check chain vs catching NullPointerException is very heavy. I try it in a jUnit test and takes several seconds to get the result!
It shouldn't be the case You might be doing something wrong
Upvotes: 11