Home  >  JDK 8

Java 8 Predicate Example

By Arvind Rai, April 26, 2014
java.util.function.Predicate is a functional interface introduced in java 8. Predicate is used for assigning a lambda expression. The functional interface is test(T t) which returns Boolean value. When we pass the object to this method, it evaluates the object over assigned lambda expression. Find the two expressions below.
Predicate<Student> maleStudent = s-> s.age >= 20 && "male".equals(s.gender);
Predicate<Student> femaleStudent = s-> s.age > 15 && "female".equals(s.gender);
First expression creates the scenario for a male student and second expression creates the scenario for female student. Find the complete example.
PredicateDemo.java
package com.concretepage.function;
import java.util.function.Function;
import java.util.function.Predicate;
public class PredicateDemo {
  public static void main(String[] args){
      Predicate<Student> maleStudent = s-> s.age >= 20 && "male".equals(s.gender);
      Predicate<Student> femaleStudent = s-> s.age > 15 && "female".equals(s.gender);
      
      Function<Student,String> maleStyle = s-> "Hi, You are male and age "+s.age;
      
      Function<Student,String> femaleStyle = s-> "Hi, You are female and age "+ s.age;
      
      Student s1 = new Student(21,"male");
      if(maleStudent.test(s1)){
          System.out.println(s1.customShow(maleStyle));
      }else if(femaleStudent.test(s1)){
          System.out.println(s1.customShow(femaleStyle));
      }      
  }    
}
In the example we have created two Predicate and then creating a student object, we are passing it to test method of Predicate.
package com.concretepage.function;
import java.util.function.Function;
public class Student {
    public int age;
    public String gender;
    public Student(int age,String gender){
        this.age = age;
        this.gender = gender;
    }
    public  String customShow(Function<Student,String> fun){
        return fun.apply(this);
    }
}
Run the example. Output will be as below.
Hi, You are male and age 21
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS








Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us