gpt4 book ai didi

java - 在流中抛出自定义异常

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:02:18 28 4
gpt4 key购买 nike

当找不到具有 firstNamelastName 的人时,我需要在我的代码中抛出 FriendNotFoundException是否可以在 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);
}

最佳答案

答案是:

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

关于java - 在流中抛出自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47410608/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com