How can I use additional variables inside of named Java Lambda Expressions, as I can do in an anonymous one? I found a workaround (method returns a Lambda), but out of curiosity: can this be formulated in pure Lambda syntax as well? I can't find an answer in the usual tutorials and references.
Please consider the following example code:
Arrays.asList(1,2,3,4,5).stream().filter( i -> i<3 ).toArray();
I can give a name to this anonymous Lambda:
Arrays.asList(1,2,3,4,5).stream().filter(LessThanThree).toArray();
[...]
Predicate<Integer> LessThanThree = i -> i<3;
But if I want to use a variable instead of the constant, the same syntax will not work. because I can't find a way to declare parameters to the named Lambda:
Edit: Thank you, dpr, for hinting that this is a matter of scope! I enhanced to following block of code to try to clarify what I'm interested in.
filterIt(3);
[...]
void filterIt(int x) {
Arrays.asList(1,2,3,4,5).stream().filter(LessThanX).toArray();
}
[...]
Predicate<Integer> LessThanX = i -> i<x; // won't compile!
The workaround seems to be a method that returns the Lambda:
private Predicate<Integer> lessThanX(int x) {
return i -> i<x;
}
But: is there a way to formulate this in pure named Lambda?