3

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);                     
}

1 Answer 1

5

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))
Sign up to request clarification or add additional context in comments.

1 Comment

And don’t think that defining two predicates makes the code more readable. But removing the redundant parentheses could do…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.