Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

234
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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");
}
over 4 years ago · Santiago Trujillo Report

0

If you map to null, the Optional becomes empty:

Optional.ofNullable(nullableObject)
    .map(object -> "A".equals(object.getStatus()) ? object : null)
    .ifPresent(object -> { throw new BusinessUncheckedException("exception message"); });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!