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

How to use optional if it is present then call a method of this object, other wise return null

Optional<CustomerEntity> findById(Integer id) {
    return Optional.ofNullable(em.find(CustomerEntity.class, Long.valueOf(id)));
}
public List<Booking> getBooking(Integer id) {
    return customerRepository.findById(id).get().getBooking();
}

The problem is findById might return null, so I want something like

customerRepository.findById(id).ifPresent().getBooking();

I could do it by manually check the ifpresent() return value, but I want to make it one line if possible.

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

>Solution :

You can use a combination of Optional.map and Optional.orElse to get the behavior you want. But I’d recommend returning an empty list instead of null, which could save you some headache at some point down the line:

return customerRepository
    .findById(id)
    .map(CustomerEntity::getBooking)
    .orElse(List.of());

By returning List.of() in the default case, you can also be sure that the returned empty list cannot be altered by adding elements afterwards.

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