Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java 8 Optional filter only if present

I have a nullable object and I’m trying to throw an exception if the object is not null and does not meet a condition.

I try this way with Optional:

Optional.ofNullable(nullableObject)
    .filter(object -> "A".equals(object.getStatus()))
    .orElseThrow(() -> new BusinessUncheckedException("exception message"));

When the object is not null, it works as I want, but otherwise, it throws the exception too (and I don’t want that).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There is a way to do that with Optional or other ways not using if object != null?

>Solution :

Assuming you aren’t doing anything with the returned object, you could use ifPresent and pass a Consumer

nullableObject.ifPresent(obj -> {
    if (!"A".equals(obj.getStatus())) {
        throw new BusinessUncheckedException("exception message");
    }
});

Note: As @Pshemo mentioned in the comments, the contract of the Consumer functional interface allows throwing only RuntimeExceptions.

Otherwise, you are better off with a if check as you’ve mentioned.

IMO, using a filter on Optional for checks like these is not that readable/intuitive. I would prefer,

if (obj != null && !"A".equals(obj.getStatus())) {     
    throw new BusinessUncheckedException("exception message");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading