Rien
Rien

Reputation: 1656

Return a predicate as a lambda in Java

In this online tutorial they use a lambda to filter a list of users:

List<User> olderUsers = users.stream().filter(u -> u.age > 30).collect(Collectors.toList());

Now I want to make a function which accepts a lambda (the u -> u.age > 30 part) so that I can put any criterion I want inside a this lambda. But I'm a bit stuck on how to implement this. I have made an empty interface Filter and I made the following methods:

public List<User> filterUsers(Filter f, List<User users>){
    return users.stream().filter(f).collect(Collectors.toList());
}
public Filter olderThan(int age) {
    return u -> u.getAge() > age;
}

But this gives a number of errors.

(I made a getter of the agefield in user). Is there a way to adjust the interface Filter or the other methods to make this work?

Upvotes: 6

Views: 8480

Answers (2)

MattPutnam
MattPutnam

Reputation: 3017

You don't need your Filter type. Just make the filterUsers method take a Predicate<User> and pass it in:

public List<User> filterUsers(Predicate<User> p, List<User> users) {
    return users.stream().filter(p).collect(Collectors.toList());
}

This would allow you to write something like:

List<User> filtered = filterUsers(u -> u.age > 10, users);

If you wanted to make your "olderThan" thing for convenience, you can write:

public Predicate<User> olderThan(int age) {
    return u -> u.getAge() > age;
}

And then you could write:

List<User> filtered = filterUser(olderThan(15), users);

Upvotes: 15

user4668606
user4668606

Reputation:

You should simply use Predicate instead of Filter.

Upvotes: 2

Related Questions