I am learning LambdaJ and everytime I need to achieve a task I have to check at existing examples and modify them in order to use lambdaj.
I have started using it but I think I'm missing something here that would like to ask you.
I'm not clear about using having
method. I don't understand how it works and how I can I use it.
I have debugged, decompiled and read its documentation but I don't find the "way of thinking" lambda.
having
javadoc says:
static HasArgumentWithValue having(A argument, org.hamcrest.Matcher matcher)
Creates an hamcrest matcher that is evalued to true if the value of the given argument satisfies the condition defined by the passed matcher.
I've used having
in examples like this:
List<User> result = filter(having(on(User.class).getAge(), greaterThan(20)), list);
I understand that having
applies a harmcrest matcher to an argument and repeats that all over the list.
But my question is how does having works? How do I think in a functional way on lambdaj?
The description of your code could look like this:
the function filter take each user from list and
apply it over function having
that retrieved the age and compare with value of 20.
This can be wrote as
private List<User> filter(List<User> users) {
final List<User> filtered = new ArrayList<>();
for(User user : users) {
if(having(user.getAge(),greaterThan(20)) {
filtered.add(user);
}
}
return filtered;
}
private boolean having(Integer age, org.hamcrest.Matcher<Integer> matcher) {
return matcher.matcher(age);
}
In other words function having take an two arguments, a value and matcher and evaluate the matcher against value. And the value argument is passed by function filter that expect boolean in result.