I need to throw FriendNotFoundException in my code when no person with firstName and lastName was not found. Is it possible to catch exception in Stream?
Now I have something like this but it's failing.
@Override
public Friend findFriend(String firstName, String lastName) throws FriendNotFoundException {
if (firstName == null || lastName ==null) {
throw new IllegalArgumentException("There are no parameters");
}
if (friends.stream().filter(x -> !firstName.equals(x.getLastName()) &&
(!lastName.equals(x.getLastName()))) != null);
{
throw new FriendNotFoundException(firstName, lastName);
}
return friends.stream().filter(
x -> (firstName.equals(x.getFirstName())) &&
(lastName.equals(x.getLastName()))).findAny().orElse(null);
}
The answer is:
return friends.stream()
.filter(x -> (firstName.equals(x.getFirstName())) &&
(lastName.equals(x.getLastName())))
.findAny()
.orElseThrow(() -> new FriendNotFoundException(firstName, lastName))
By the way to have code more elegant my proposition is to do something like this:
Predicate<Person> firstNamePredicate = x -> firstName.equals(x.getFirstName())
Predicate<Person> lastNamePredicate = x -> firstName.equals(x.getLasttName())
return friends.stream()
.filter(firstNamePredicate.and(lastNamePredicate))
.findAny()
.orElseThrow(() -> new FriendNotFoundException(firstName, lastName))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With