Over

120,000

Worldwide

Saturday - Sunday CLOSED

Mon - Fri 8.00 - 18.00

Call us

 

Java Functional Interfaces – Predicate & BiPredicate

Java Functional InterfacesPredicate & BiPredicate

This section describes the functional interfaces Predicate & BiPredicate defined in java.util.Function package in Java 8.

What is it?

 Predicate: A functional interface that represents an operation that accepts one argument and returns a Boolean (true or false) value.  

@FunctionalInterface

public interface Predicate<T>

{

boolean test(T t) ;

}

.

Predicate interface contains some other methods like:

1.isEqual(): Returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).
2. and(): It does logical AND of the predicate on which it is called and another predicate.
3.or(): It does logical OR of the predicate on which it is called and another predicate.
4.negate(): It does logical negation of the predicate on which it is called.

.

 BiPredicate: A functional interface that represents an operation that accepts one two arguments and returns a Boolean (true or false) value.  

@FunctionalInterface

public interface BiPredicate<T,U>

{

Boolean test(T t, U u);

}

.

BiPredicate interface also contains and(), or() and negate() methods.

Why it was introduced?

.

 It improves maintainability and readability of the code, and helps in unit testing separately.

.

When should you use it?

.

 It can be used when an object needs to be evaluated for a given test condition and a Boolean value needs to be returns based on whether the condition is satisfied or not.
 It can be used to filter object in a collection.

.

Examples

.

The examples illustrated below use the following Employee POJO class:

.

package org.examples;

.

public class Employee {

      private String name;

      private Integer hourRate;

      public String getName() {

        return name;

      }

      public void setName(String name) {

        this.name = name;

      }

      public Integer getHourRate() {

        return hourRate;

      }

      public void setHourRate(Integer hourRate) {

        this.hourRate = hourRate;

      }

      public Employee(String name, Integer hourRate) {

        super();

        this.name = name;

        this.hourRate = hourRate;

      }

                   @Override

      public String toString() {

        return “Employee [name=” + name + “, hourRate=” + hourRate + “]”;

      }

}

.

.

 Predicate

.

1.This implementation shows simple usage of Predicate to print the names of employees starting with particular string from a list of Employee objects.

package org.examples;

.

import java.util.Arrays;

import java.util.List;

import java.util.function.Predicate;

import java.util.stream.Collectors;

.

public class PredicateExample2 {

  public static void main(String[] args)

  {

List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10),

           new Employee(“Robert”, 50),

          new Employee(“David”, 30),

          new Employee(“Abhi”, 20));  

.

  //Names of employees starting with A    

employees.forEach(emp -> {

        if(nameStartsWithPredicate(“A”).test(emp))

          System.out.println(emp);

        });

  }

  

  public static Predicate<Employee> nameStartsWithPredicate(String str)

  {

    return emp -> emp.getName().startsWith(str);

  }

}

Output:

Employee [name=Abhi, hourRate=20]

.

.

2.This implementation shows usage of Predicate in a filter. It filters a list of Employee objects to find a list of employees having hourRate greater than 30, and a list of employees having hourRate less than 30.

package org.examples;

.

import java.util.Arrays;

import java.util.List;

import java.util.function.Predicate;

import java.util.stream.Collectors;

.

public class PredicateExample2 {

  public static void main(String[] args)

  {

List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10),

                    new Employee(“Robert”, 50),

                new Employee(“David”, 30),

                new Employee(“Abhi”, 20));  

      

        // List of employees with rate greater than 30

    List<Employee> employeeGrp1 =

                   filterEmployees(employees, getRateGreaterThanPredicate(30));     

    System.out.println(Employees having rate greater than 30:”+ employeeGrp1);

    

        // List of employees with rate less than 30

    List<Employee> employeeGrp2 =

                     filterEmployees(employees, getRateLessThanPredicate(30));    

    

             System.out.println(\nEmployees having rate less than 30:”+ employeeGrp2);

  }

  

  public static Predicate<Employee> getRateGreaterThanPredicate(Integer rate)

  {

    return emp -> emp.getHourRate() > rate;

  }

  public static Predicate<Employee> getRateLessThanPredicate(Integer rate)

  {

    return emp -> emp.getHourRate() < rate;

  }

  

.

  public static List<Employee>

filterEmployees(List<Employee> employees, Predicate<Employee> predicate)

  {

    return employees.stream().filter(predicate).collect(Collectors.toList());

  }

}

Output:

Employees having rate greater than 30: [Employee [name=Robert, hourRate=50]]

.

Employees having rate less than 30:[Employee [name=Jack, hourRate=10], Employee [name=Abhi, hourRate=20]]

.

.

.

.

.

.

.

.

.

3.This implementation shows Predicate chaining using and(), or(), and negate() methods.

.

package org.examples;

.

import java.util.Arrays;

import java.util.List;

import java.util.function.Predicate;

import java.util.stream.Collectors;

.

public class PredicateExample3 {

  public static void main(String[] args)

  {

List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10),

               new Employee(“Robert”, 50),

                new Employee(“David”, 30),

                new Employee(“Abhi”, 20));  

     

System.out.println(“Employees with names not starting with A:”);    

    

       employees.forEach(emp -> {

                if(nameStartsWithPredicate(“A”).negate().test(emp))

                    System.out.println(emp);

                });

        

       System.out.println(“\nEmployees with names starting A or J:”);    

     

      employees.forEach(emp -> {               

          if(nameStartsWithPredicate(“J”).or(nameStartsWithPredicate(“A”)).test(emp))

                   System.out.println(emp);

               });

.

     System.out.println(“\nEmployees with names starting R and rate greater than 30:”);    

    employees.forEach(emp -> {

      if(nameStartsWithPredicate(“R”).and(getRateGreaterThanPredicate(30)).test(emp))

                      System.out.println(emp);

           });

      }

  

  public static Predicate<Employee> nameStartsWithPredicate(String str)

  {

    return emp -> emp.getName().startsWith(str);

  }

.

  public static Predicate<Employee> getRateGreaterThanPredicate(Integer rate)

  {

    return emp -> emp.getHourRate() > rate;

  }

}

Output:

Employees with names not starting with A:

Employee [name=Jack, hourRate=10]

Employee [name=Robert, hourRate=50]

Employee [name=David, hourRate=30]

.

Employees with names starting A or J:

Employee [name=Jack, hourRate=10]

Employee [name=Abhi, hourRate=20]

.

Employees with names starting R and rate greater than 30:

Employee [name=Robert, hourRate=50]

.

.

 BiPredicate

.

1.This implementation shows usage of BiPredicate to find employees with names matching the provided length in a list of Employee objects.

package org.examples;

.

import java.util.Arrays;

import java.util.List;

import java.util.function.BiPredicate;

.

public class BiPredicateExample1 {

  public static void main(String[] args)

  {

List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10),

                    new Employee(“Robert”, 50),

                new Employee(“David”, 30),

                new Employee(“Abhi”, 20));  

    System.out.println(“Employees with name length 6:”);

             employees.forEach(emp->

              {

                if(getNameLengthPredicate().test(emp, 6))

                  System.out.println(emp);

              });

    

    System.out.println(\nEmployees with name length 4:”);

    employees.forEach(emp->

     {

                 if(getNameLengthPredicate().test(emp, 4))

                    System.out.println(emp);

     });

  }

  

  public static BiPredicate<Employee,Integer> getNameLengthPredicate()

  {

    return (emp,len) -> emp.getName().length() == len;

  }

}

.

Output:

Employees with name length 6:

Employee [name=Robert, hourRate=50]

.

Employees with name length 4:

Employee [name=Jack, hourRate=10]

Employee [name=Abhi, hourRate=20]

.

Leave a Reply

Your email address will not be published. Required fields are marked *

Working Hours

  • Monday 9am - 6pm
  • Tuesday 9am - 6pm
  • Wednesday 9am - 6pm
  • Thursday 9am - 6pm
  • Friday 9am - 6pm
  • Saturday Closed
  • Sunday Closed