Posts Tagged ‘Java8Predicate’

In addition to the new lambda syntax, Java SE8 adds a number of new functional interfaces. One of the most useful is called the Predicate Interface which is an interface that has a single boolean method named Test, that you can use to wrap up your conditional processing, and make conditional code a lot cleaner.

Go through the following example and you will get an understanding of Predicate Interface

package com.suhas;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;


public class PredicateInterfaceTest {

    public static void main(String[] args) {

        List<Person> personList = new ArrayList<>();
        personList.add(new Person("Sam", 10));
        personList.add(new Person("Smith", 9));
        personList.add(new Person("Zayn", 6));
        personList.add(new Person("Nathan", 1));

        Predicate<Person> agePredicate = person -> person.getAge() > 5;

        Predicate<Person> namePredicate = person -> person.getName().equals("Zayn");

        Predicate<Person> nameAndAgePredicate = namePredicate.and(person -> person.getAge() < 5);

        personList.forEach(person -> {
            if (agePredicate.test(person))
                System.out.println("Matching Record Found for Age Predicate :: " + person.getName());
            if (namePredicate.test(person))
                System.out.println("Matching Record Found for Name Predicate :: " +  person.getName());
            if (nameAndAgePredicate.test(person))
                System.out.println("Matching Record Found for Name and Age Predicate :: " +  person.getName());

        });

    }
}
Advertisements