Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw custom exception in stream

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);                     
}
like image 219
Donne Avatar asked Jun 25 '26 12:06

Donne


1 Answers

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))
like image 132
Pulkownik Avatar answered Jun 27 '26 01:06

Pulkownik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!