从JAVA流获取对象

从JAVA流获取对象,java,object,methods,return,java-stream,Java,Object,Methods,Return,Java Stream,我正在尝试使用流按名字和姓氏查找朋友。是否可以从此流返回对象?像那个姓和那个名字的朋友?因为现在返回是不匹配的 @Override public Friend findFriend(String firstName, String lastName) throws FriendNotFoundException { if (firstName == null || lastName ==null) { throw new IllegalArgumentExceptio

我正在尝试使用流按名字和姓氏查找朋友。是否可以从此流返回对象?像那个姓和那个名字的朋友?因为现在返回是不匹配的

@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;
@覆盖
公共好友findFriend(字符串firstName,字符串lastName)引发FriendNotFoundException{
if(firstName==null | | lastName==null){
抛出新的IllegalArgumentException(“没有参数”);
}
列表结果=friends.stream()
.filter(x->(firstName.equals(x.getFirstName())&&
(lastName.equals(x.getLastName()))
.collect(Collectors.toList());
返回结果;
像这样利用:

或返回一个,即:

@覆盖
公共可选findFriend(字符串firstName,字符串lastName)引发FriendNotFoundException{
if(firstName==null | | lastName==null){
抛出新的IllegalArgumentException(“没有参数”);
}
return friends.stream()
.filter(x->firstName.equals(x.getFirstName())&&
lastName.equals(x.getLastName())
)
.findFirst();
}

这意味着您要重写的方法也必须声明为返回一个
可选的
,如果需要的话,在继承层次结构上依此类推。

调用
findAny()
findFirst()
而不是
collect()
。这是一个很好的提示。您可能需要使用
findAny()
,但是。对于大型流可能更有效。@MalteHartwig true,我建议在使用parallelStream执行批量操作时使用
findAny
,因为在这种情况下使用
findAny
比使用
findFirst
约束更小。
return friends.stream()
              .filter(x -> firstName.equals(x.getFirstName()) && 
                            lastName.equals(x.getLastName())
                     )
              .findFirst().orElse(null);
@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();
}