Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java lambda expression - how interface name was omitted?

Tags:

java

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.

like image 602
Alexei Martianov Avatar asked Jul 20 '26 19:07

Alexei Martianov


2 Answers

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.

like image 74
Andrew Tobilko Avatar answered Jul 23 '26 09:07

Andrew Tobilko


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.

like image 41
Alexey Soshin Avatar answered Jul 23 '26 07:07

Alexey Soshin