1

I am trying to find Friend by firstName and lastName using stream. Is it possible to return object from this stream? Like friend with that name and lastname? Because now return is mismatched.

@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
  • 2
    Call findAny() or findFirst() instead of collect(). Commented Nov 20, 2017 at 23:44

1 Answer 1

2

utilize findFirst like so:

return friends.stream()
              .filter(x -> firstName.equals(x.getFirstName()) && 
                            lastName.equals(x.getLastName())
                     )
              .findFirst().orElse(null);

or return an Optional<Friend> i.e:

@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();
}

which then means the method you're overriding must also be declared to return an Optional<Friend> and so forth up the inheritance hierarchy if needed.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice hint with the Optional. You might want to use findAny(), though. It might be more efficient for large streams.
@MalteHartwig true, I would recommend findAny when performing bulk operations with parallelStream as it's less constraining to use findAny in such case rather than to use findFirst.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.