I was looking around for a while but could not seem to find the right answer. I am trying to reduce my code since I have a project and want to use lambda expressions. I am new to lambda and still practicing it, I came across "EXCEPTION HANDLING" with lambda in general, however, for my specific problem I could not seem to find.
I have a whole project to fix but here is an example of a code I want to reduce.
Code:
for (Customer allCustomers : cust.getAllCustomers()) {
if (customer.getEmail().equals(allCustomers.getEmail()))
throw new CustomerAlreadyExists(
"ERROR: Cannot add customer. email is already in use.");
}
What I have tried:
cust.getAllCustomers()
.stream()
.filter(x -> x.getEmail().equals(customer.getEmail())
.forEach(throw new CustomerAlreadyExists(
"ERROR: Cannot add customer. email is already in use."));
My problem seems to be with throwing the exception. (Will not compile) otherwise I think the expression is fine. is there a way to throw an exception with a one liner?
thanks. Still learning.