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 age
field in user
).
Is there a way to adjust the interface Filter
or the other methods to make this work?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With