Java 8 : Predicate

Predicate is a functional interface, which has only one boolean method named test that you can use for any conditional coding and make your code lot more cleaner and readable. You might pass an object to a Predicate and the predicate will evaluate if it meets the condition returning true or false. Lets see this by an exmaple. We will use a Employee class with following fields and custom methods:


package mynotes.java8.features;

public class Employee {

private String name;
private int age;
private int salary;

public Employee(String name, int age, int salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}

@Override
public String toString() {
return "Employee [name=" + name + ", age=" + age + ", salary=" + salary
+ "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}

}

Now suppose we have a list of employees and we want to find out the all the employees having a salary greater than 100,000. Lets see how we do this using a Predicate interface. We will be using inner class implementation in the following:


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

public class PredicateInnerClass {

public static void main(String[] args) {
List<Employee> empList=new ArrayList<Employee>();
empList.add(new Employee("John", 27, 98000));
empList.add(new Employee("Jane", 25, 80000));
empList.add(new Employee("Max", 28, 110000));
empList.add(new Employee("Matt", 32, 150000));

Predicate<Employee> pred=new Predicate<Employee>() {
@Override
public boolean test(Employee emp) {
return (emp.getSalary()>100000);
}
};

for (Employee employee : empList) {
if(pred.test(employee)){
System.out.println(employee);
}
}
}

}

Output:


Employee [name=Max, age=28, salary=110000]
Employee [name=Matt, age=32, salary=150000]

As you can see from above code, we have overidden the test method and checked the conditions. Then we used a for each loop on employee list and use the predicate object to test the condition and proceed. At first it may feel like we could have use out conditional statement directly inside which is write, but using preicate decouples the logic with the display.

As we know that predicate is a functional interface, hence we can use lambda expressions and make our code more concise. Lets see the above example using lambda expressions:


public class PredicateUsingLambda {

public static void main(String[] args) {
List<Employee> empList=new ArrayList<Employee>();
empList.add(new Employee("John", 27, 98000));
empList.add(new Employee("Jane", 25, 80000));
empList.add(new Employee("Max", 28, 110000));
empList.add(new Employee("Matt", 32, 150000));

Predicate<Employee> predSalary=(e)->e.getSalary()>100000;

empList.forEach(tempEmp ->{
if(predSalary.test(tempEmp)){
System.out.println(tempEmp);
}
});
}
}

As you can see, the whole predicate conditions fits in just one line and later we have used the ne forEach method and used lambda expressions there also. Note that since the Predicate and the empList already has Employee type at the time of declaration, so we do not have to metion type again inside. Lets add more predicates and move the display list logic to a new method for a more cleaner code.


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

public class PredicateUsingLambda {
    
    public static void main(String[] args) {
        List<Employee> empList=new ArrayList<Employee>();
        empList.add(new Employee("John", 27, 98000));
        empList.add(new Employee("Jane", 25, 80000));
        empList.add(new Employee("Max", 28, 110000));
        empList.add(new Employee("Matt", 32, 150000));
        
        Predicate<Employee> predSalary=(e)->e.getSalary()>100000;
        System.out.println("=================Employees having salary > 100000================");
        displayList(empList, predSalary);
        Predicate<Employee> predAge=(e)->e.getAge()<30;
        System.out.println("===================Employees having age <30==================");
        displayList(empList, predAge);
    }

    private static void displayList(List<Employee> empList,
            Predicate<Employee> pred) {
        empList.forEach(tempEmp ->{
            if(pred.test(tempEmp)){
                System.out.println(tempEmp);
            }
        });
    }
}

Output:


=================Employees having salary > 100000================
Employee [name=Max, age=28, salary=110000]
Employee [name=Matt, age=32, salary=150000]
===================Employees having age <30==================
Employee [name=John, age=27, salary=98000]
Employee [name=Jane, age=25, salary=80000]
Employee [name=Max, age=28, salary=110000]

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: