Don*_*nne 3 java exception java-stream
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);
}
Run Code Online (Sandbox Code Playgroud)
答案是:
return friends.stream()
.filter(x -> (firstName.equals(x.getFirstName())) &&
(lastName.equals(x.getLastName())))
.findAny()
.orElseThrow(() -> new FriendNotFoundException(firstName, lastName))
Run Code Online (Sandbox Code Playgroud)
顺便说一句,让代码更优雅,我的主张就是这样做:
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))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
253 次 |
最近记录: |