我试图通过firstName和lastName使用stream找到Friend。是否可以从此流返回对象?喜欢那个名字和姓氏的朋友?因为现在回报不匹配。
@Override
public Friend findFriend(String firstName, String lastName) throws FriendNotFoundException {
if (firstName == null || lastName ==null) {
throw new IllegalArgumentException("There is no parameters");
}
List<Friend> result = friends.stream()
.filter(x -> (firstName.equals(x.getFirstName())) &&
(lastName.equals(x.getLastName()))))
.collect(Collectors.toList());
return result;
答案 0 :(得分:2)
像这样使用findFirst
:
return friends.stream()
.filter(x -> firstName.equals(x.getFirstName()) &&
lastName.equals(x.getLastName())
)
.findFirst().orElse(null);
或返回Optional<Friend>
,即:
@Override
public Optional<Friend> findFriend(String firstName, String lastName) throws FriendNotFoundException {
if (firstName == null || lastName == null) {
throw new IllegalArgumentException("There is no parameters");
}
return friends.stream()
.filter(x -> firstName.equals(x.getFirstName()) &&
lastName.equals(x.getLastName())
)
.findFirst();
}
这意味着,如果需要,还必须声明您重写的方法返回Optional<Friend>
等等继承层次结构。