从流JAVA获取对象

时间:2017-11-20 23:42:36

标签: java object methods return java-stream

我试图通过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;

1 个答案:

答案 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>等等继承层次结构。