Skip to content

Latest commit

 

History

History
41 lines (31 loc) · 1.32 KB

Java.md

File metadata and controls

41 lines (31 loc) · 1.32 KB

Java Syntax I feel odd

Anonymous Classes & Lambda Expression

Reference: Oracle Doc--Lambda Expressions Oracle Doc--Anonymous Classes

Here is the anonymous class sample code.

interface CheckPerson {
    boolean test(Person p);
}

printPersons(
    roster,
    new CheckPerson() { //
        public boolean test(Person p) {
            return p.getGender() == Person.Sex.MALE
                && p.getAge() >= 18
                && p.getAge() <= 25;
        }
    }
);

Below is the Lambda Expressions for this case:

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
);