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

Time:11-06

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.

CodePudding user response:

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.

  • Related