当没有找到FriendNotFoundException
和firstName
的人时,我需要在我的代码中抛出lastName
。 是否可以在Stream中捕获异常?
现在我有类似的东西,但它失败了。
@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);
}
答案 0 :(得分:5)
答案是:
TestFixtureTearDown
顺便说一下,让代码更优雅,我的主张就是做这样的事情:
return friends.stream()
.filter(x -> (firstName.equals(x.getFirstName())) &&
(lastName.equals(x.getLastName())))
.findAny()
.orElseThrow(() -> new FriendNotFoundException(firstName, lastName))