I'm reading oracle tutorial on lambda expressions: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
To specify the search criteria, you implement the CheckPerson interface:
interface CheckPerson {
boolean test(Person p); }
then use it
printPersons(
roster,
new CheckPerson() {
public boolean test(Person p) {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
}
);
then
The CheckPerson interface is a functional interface. A functional interface is any interface that contains only one abstract method. (A functional interface may contain one or more default methods or static methods.) Because a functional interface contains only one abstract method, you can omit the name of that method when you implement it. To do this, instead of using an anonymous class expression, you use a lambda expression, which is highlighted in the following method invocation:
printPersons(
roster,
(Person p) -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
);
They say they omit the method, I see no test in lambda - that is clear. But they also dropped name of interface CheckPerson. Why is it not mentioned in explanation? Do we use the CheckPerson interface in lambda or not?
ADDED on 2019/08/29:
Thank you Alexey Soshin, Andrew Tobilko, Andreas (in the time order of answering), for your answers! I see your answers as complimenting each other to give full picture and therefore I cannot choose only one as accepted.
Do we use the CheckPerson interface in lambda or not?
We don't use it, we define it. We give it an implementation. We implement that interface by writing a lambda expression.
"in lambda" is your misunderstanding, because the lambda is an instance of that interface.
They say they omit the method, I see no test in lambda - that is clear. But they also dropped name of interface CheckPerson.
It's not about "dropping" or "omitting" something. It's about replacing one syntactical construction with another. You replace an anonymous class with a lambda expression to make your code more expressive and less verbose.
It's called SAM (single abstract method) type in Java, and yes, interface is still used.
Let's look the signature of printPersons:
public static void printPersons(List<Person> roster, CheckPerson tester)
So, Java compiler knows that if you provide it with a lambda, this lambda should comply to single method CheckPerson provides.
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