Selvin :
Below is my Java 8 code, when I run Sonar, I am getting "Call "Optional#isPresent()" before accessing the value." message. Please help me how to add isPresent()
for subPlan.getTaxWthholding().getFederalTaxDetails().getFederalTaxPercentage().
SubPlan maxSubPlan = subPlanList.stream()
.filter(s -> s.getIsSelected())
.max(Comparator.comparing(subPlan ->
subPlan.getTaxWthholding().getFederalTaxDetails().getFederalTaxPercentage()))
.get();
Eran :
I don't think it wants you to add isPresent
inside the Comparator
.
The problem is probably the last get()
.
max()
may return an empty Optional
(if subPlanList
is empty, or if the filter
step filtered out all the elements), so you should replace get()
with either orElse(defaultValue)
, orElseGet()
or orElseThrow()
.