'How to do Java Optional if present do something or else throw?
What I want to do is, updating a customer if it is present but if there is no customer then throw an exception. But I could not find the correct stream function to do that. How can I achieve this ?
public Customer update(Customer customer) throws Exception {
Optional<Customer> customerToUpdate = customerRepository.findById(customer.getId());
customerToUpdate.ifPresentOrElse(value -> return customerRepository.save(customer),
throw new Exception("customer not found"));
}
I could not return the value coming from save function because it is saying that it is void method and not expecting return value.
Solution 1:[1]
As Guillaume F. already said in the comments, you could just use orElseThrow here:
Customer customer = customerRepository.findById(customer.getId())
.orElseThrow(() -> new Exception("customer not found"));
return customerRepository.save(customer);
By the way, avoid throwing Exception, as that exception is too broad. Use a more specific type, like NotFoundException.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
