Java 8 – Predicate Interface

Posted: June 8, 2018 in Java8
Tags: , , ,

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s