Predicates in Java8

Predicates are boolean valued functions which returns true/false based on some conditions. Simple.

Predicate<T> in java is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

Now let’s see how to use Predicates.

We have one below Employee class and we want to filter out Employees based on some given conditions.

public class Employee {
    private int empId;
    private String empName;
    private String gender;
    private String salary;
    // and their getters/setters
}

Use Cases

  • Print names of all male Employees.

To achieve that we will write one predicate MaleEmployeePredicate 

class MaleEmployeePredicate { 
    public static Predicate<Employee> isMaleEmp() { 
       return emp -> emp.getGender().equalsIgnoreCase("Male"); 
    }
}

After  creating Predicates lets use them.

Predicate<Employee> pred = MaleEmployeePredicate.isMaleEmp();
employees.stream()
    .filter(pred)
    .map(Employee::getName)
    .forEach(System.out::println);

So the above statement will print Names of all male Employees.

 

Method Summary in Predicate Interface

Modifier and Type Method and Description
default Predicate<T> and(Predicate<? super T> other)
Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.
static <T> Predicate<T> isEqual(Object targetRef)
Returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).
default Predicate<T> negate()
Returns a predicate that represents the logical negation of this predicate.
default Predicate<T> or(Predicate<? super T> other)
Returns a composed predicate that represents a short-circuiting logical OR of this predicate and another.
boolean test(T t)
Evaluates this predicate on the given argument.

Lets use them one by one.

  • and(Predicate<? super T> other)

Print name all male Employees who has Salary more than 5000.  So we need to create one more Salary Predicate.

class SalaryEmployeePredicate { 
  public static Predicate<Employee> isSalaryAbove5000() { 
    return emp -> emp.getSalary() > 5000; 
  }
}

// and use them like this
Predicate<Employee> pred = MaleEmployeePredicate.isMaleEmp()
                       .and(SalaryEmployeePredicate.isSalaryAbove5000());

employeeList.stream()
            .filter(pred)
            .map(Employee:: getName)
            .forEach(System.out::println);

 

  • or(Predicate<? super T> other)

Print name of all Male Employees or their whom Salary is above 5000.

Predicate<Employee> pred = MaleEmployeePredicate.isMaleEmp()
 .or(SalaryEmployeePredicate.isSalaryAbove5000());

employeeList.stream()
 .filter(pred)
 .map(Employee:: getName)
 .forEach(System.out::println);

 

  • negate()

Print names of all those Employees who are not in English Department.

class DepartmenEmployeePredicate { 
   public static Predicate<Employee> isEnglishDeptEmp() { 
    return emp -> emp.getDepartment().contains("English"); 
   }
}

Predicate<Employee> pred = 
DepartmenEmployeePredicate.isEnglishDeptEmp().negate();

employees.stream().filter(pred)
                  .map(Employee:: getName)
                  .forEach(System.out::println);

 

  • isEqual(Object targetRef)

Consider, we have overridden equals() method in Employee class based on their empId and empName.

Predicate<Employee> pred = 
          Predicate.isEqual(new Employee("Akash", 9, 3000, "Male"));

System.out.println(pred.test(new Employee("Akash", 9, 3000, "Male"))); // will print true
System.out.println(pred.test(new Employee("Kailash", 10, 3000, "Male"))); // will print false

 

  • test(T t)
Predicate<Employee> pred = MaleEmployeePredicate.isMaleEmp()
                 .and(SalaryEmployeePredicate.isSalaryAbove3000());

System.out.println(pred.test(new Employee("Kailash", 10, 4000, "Male"))); // Will print true
System.out.println(pred.test(new Employee("Pavan", 20, 2000, "Male"))); // Will print false

 

GIT Repository: – https://tektutorial.com/2018/06/11/predicates-in-java8/

 

Hope this clears your doubt about Predicate!!