Home > database >  How to check the field of an object on NPE and condition simultaneously through Optional? And if eve
How to check the field of an object on NPE and condition simultaneously through Optional? And if eve

Time:11-16

I use Java 8 and have an issue with how to check objects through Optional. It should be like

Optional.ofNullable(person)
        .map(Person::getAge)
        .filter(age -> age > 25)
        .orElseThrow(new CustomException())

However, this code returns the value, but I don't need this. How fix it? Code should be like this

If (noNPE && person.getAge() > 25) {
       // do nothing
} else {
       throw new CustomException();
}

I don't need return value due to sonar throw warnings.

CodePudding user response:

The only thing that needs to be fixed in your code is the API usage, otherwise it won't compile:

Optional.ofNullable(person)
        .map(Person::getAge)
        .filter(age -> age > 25)
        .orElseThrow(CustomException::new);

(orElseThrow() needs to be fed with a Supplier)

There is no problem in ignoring the returned value.

Try @SuppressWarning("unused") or //NOSONAR to silence SonarQubes false positive.

CodePudding user response:

You could leverage ifPresent() as the predication in the if statement:

if Optional.ofNullable(person)
        .map(Person::getAge)
        .filter(age -> age > 25)
        .orElseThrow(new CustomException())
        .isPresent() {
       // do nothing
} else {
       throw new CustomException();
}
  • Related