Search code examples
javajava-8option-type

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).

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");
    }