Kannan Thangadurai
Kannan Thangadurai

Reputation: 1135

How lambda expression works with Predicate?

I need more clarification about lambda expression. How 'p' represents List<Person> people? Could you explain clear to me

List<Person> people = new ArrayList<>();
people.add(new Person("Mohamed", 69));
people.add(new Person("Doaa", 25));
people.add(new Person("Malik", 6));
Predicate<Person> pred = (p) -> p.getAge() > 65;

Upvotes: 5

Views: 2061

Answers (2)

user2982622
user2982622

Reputation: 113

Lambdas in java it is just a syntax shugar for anonymous classes

Code from you example is equal to

List<person> people = new ArrayList<>();
people.add(new Person("Mohamed", 69));
people.add(new Person("Doaa", 25));
people.add(new Person("Malik", 6));

Predicate<person> pred = new Predicate<person>() {
    public boolean test(person p) {
        return p.getAge() > 65;
    }
}

To simplify syntax in java you can skip type declaration in lambda expression and add only name of value, like you did.

Predicate<person> pred = (p) -> p.getAge() > 65;

Or if you want, you can write something like this

Predicate<person> pred = (person p) -> p.getAge() > 65;

Its to be noted you can skip type declaration only if it can be counted from lambda code somehow. For example

Comparator<String> comp
= (firstStr, secondStr) // Same as (String firstStr, String secondStr)
    -> Integer.compare(firstStr.length(),secondStr.length());

Upvotes: 1

Tunaki
Tunaki

Reputation: 137084

No, p is not a List<Person> but a Person.

Predicate<Person> pred = p -> p.getAge() > 65;

This lambda expression declares 1 formal parameter and returns a boolean. As such, it can be represented as a Predicate (because the Predicate interface has a single functional method with this exact signature, called test). The type of p will be determined by the type of the Predicate you are creating.

For example, in the following code, p will be a List<Person>:

Predicate<List<Person>> predicate = p -> p.isEmpty();

Upvotes: 7

Related Questions