Optional.ofNullable + Optional value should only be accessed after calling isPresent()

Hi,

The code still needs a call to aliMnsId.isPresent(). See this example:

Optional<String> aliMnsId = Optional.empty();
if (Optional.ofNullable(aliMnsId).isPresent()) {
    aliMnsId.get();
}

It causes the exception:

Exception java.util.NoSuchElementException: No value present
        at Optional.get (Optional.java:143)

And to avoid this error, you need a aliMnsId.isPresent() as SonarQube suggests…

if (Optional.ofNullable(aliMnsId).isPresent() && aliMnsId.isPresent())

But at this point, you could simply write if (aliMnsId != null && aliMnsId.isPresent())

1 Like