Reputation: 61
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;
Upvotes: 1
Views: 320
Reputation: 56469
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.
Upvotes: 2