Java 在流中抛出自定义异常
我需要在代码中抛出Java 在流中抛出自定义异常,java,exception,java-stream,Java,Exception,Java Stream,我需要在代码中抛出FriendNotFoundException,如果找不到名为firstName和lastName的人是否可以捕获流中的异常? 现在我有了这样的东西,但它失败了 @Override public Friend findFriend(String firstName, String lastName) throws FriendNotFoundException { if (firstName == null || lastName ==null) {
FriendNotFoundException
,如果找不到名为firstName
和lastName
的人是否可以捕获流中的异常?
现在我有了这样的东西,但它失败了
@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);
}
答案是:
return friends.stream()
.filter(x -> (firstName.equals(x.getFirstName())) &&
(lastName.equals(x.getLastName())))
.findAny()
.orElseThrow(() -> new FriendNotFoundException(firstName, lastName))
顺便说一句,为了让代码更优雅,我的建议是这样做:
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))
Predicate firstName Predicate=x->firstName.equals(x.getFirstName())
谓词lastname Predicate=x->firstName.equals(x.getLasttName())
return friends.stream()
.filter(firstNamePredicate.and(lastNamePredicate))
.findAny()
.OrelsThrow(()->new FriendNotFoundException(firstName,lastName))
,不要认为定义两个谓词会使代码更具可读性。但是删除多余的括号可以…