Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 262
Rien Avatar asked Dec 06 '22 22:12

Rien


1 Answers

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);
like image 139
MattPutnam Avatar answered Dec 17 '22 18:12

MattPutnam