Home  >  Java 8

Java Predicate

By Arvind Rai, February 26, 2019
Predicate functional interface is introduced in Java 8. Java Predicate represents a predicate of one argument. A Predicate is a boolean-valued function. Java Predicate is a functional interface and belongs to java.util.function package. The functional method of Predicate is test(T t). The other methods of Predicate are test, isEqual, and, or, negate and not. The method not has been introduced in Java 11. Here on this page we will provide examples of Predicate with all its methods.

1. test(T t)

boolean test(T t) 
test is the functional method of Predicate. It evaluates this predicate on the given argument.
Example-1:
PredicateTestDemo1.java
package com.concretepage;
import java.util.function.Predicate;
public class PredicateTestDemo1 {
  public static void main(String[] args) {
	// Is username valid
	Predicate<String> isUserNameValid = u -> u != null && u.length() > 5 && u.length() < 10;
	System.out.println(isUserNameValid.test("Mahesh")); //true

	// Is password valid
	Predicate<String> isPasswordValid = p -> p != null && p.length() > 8 && p.length() < 15;
	System.out.println(isPasswordValid.test("Mahesh123")); //true
	
	// Word match
	Predicate<String> isWordMatched = s -> s.startsWith("Mr.");
	System.out.println(isWordMatched.test("Mr. Mahesh")); //true
	
	//Odd numbers
	Predicate<Integer> isEven = n -> n % 2 == 0;
	for(int i = 0 ; i < 5 ; i++) {
	  System.out.println("Is "+ i + " even: " + isEven.test(i));
	}
  }
} 
Output
true
true
true
Is 0 even: true
Is 1 even: false
Is 2 even: true
Is 3 even: false
Is 4 even: true 
Example-2:
PredicateTestDemo2.java
package com.concretepage;
import java.util.function.Function;
import java.util.function.Predicate;
public class PredicateTestDemo2 {
  public static void main(String[] args){
    Predicate<Student> maleStudent = s-> s.getAge() >= 20 && "male".equals(s.getGender());
    Predicate<Student> femaleStudent = s-> s.getAge() > 18 && "female".equals(s.getGender());
    
    Function<Student,String> maleStyle = s-> "Hi, You are male and age "+s.getAge();
    Function<Student,String> femaleStyle = s-> "Hi, You are female and age "+ s.getAge();
    
    Student s1 = new Student("Gauri", 20,"female");
    if(maleStudent.test(s1)){
        System.out.println(s1.customShow(maleStyle));
    }else if(femaleStudent.test(s1)){
        System.out.println(s1.customShow(femaleStyle));
    }      
  } 
} 
Student.java
package com.concretepage;
import java.util.function.Function;
public class Student {
  private String name;
  private int age;
  private String gender;
  private int marks;
  public Student(String name, int age, String gender){
    this.name = name;	
    this.age = age;
    this.gender = gender;
  }  
  public Student(String name, int age, String gender, int marks){
    this.name = name;
    this.age = age;
    this.gender = gender;
    this.marks = marks;
  }
  public String getName() {
    return name;
  }
  public int getAge() {
    return age;
  }
  public String getGender() {
    return gender;
  }
  public int getMarks() {
    return marks;
  }
  public  String customShow(Function<Student,String> fun){
    return fun.apply(this);
  }
  public String toString(){ 
    return name+" - "+ age +" - "+ gender + " - "+ marks;  
  }  
} 
Output
Hi, You are female and age 20 

2. and(Predicate<? super T> other)

default Predicate<T> and(Predicate<? super T> other) 
and is the default method of Predicate that returns a composed predicate that represents the short-circuiting logical AND of this predicate and the other predicate. When evaluating the composed predicate, if this predicate is false then other predicate will not be evaluated. In case of error, if this predicate throws error then other predicate will not be evaluated.
PredicateAndDemo.java
package com.concretepage;
import java.util.function.Predicate;
public class PredicateAndDemo {
  public static void main(String[] args) {
	Predicate<Student> isMaleStudent = s -> s.getAge() >= 20 && "male".equals(s.getGender());
	Predicate<Student> isFemaleStudent = s -> s.getAge() > 18 && "female".equals(s.getGender());
	Predicate<Student> isStudentPassed = s -> s.getMarks() >= 33;

	// Testing if male student passed.
	Student student1 = new Student("Mahesh", 22, "male", 30);
	Boolean result = isMaleStudent.and(isStudentPassed).test(student1);
	System.out.println(result); //false

	// Testing if female student passed.
	Student student2 = new Student("Gauri", 19, "female", 40);
	result = isFemaleStudent.and(isStudentPassed).test(student2);
	System.out.println(result); //true
  }
} 
Output
false
true 

3. or(Predicate<? super T> other)

default Predicate<T> or(Predicate<? super T> other) 
or is the default method of Predicate that returns a composed predicate that represents the short-circuiting logical OR of this predicate and the other predicate. When evaluating the composed predicate, if this predicate is true then other predicate will not be evaluated. In case of error, if this predicate throws error then other predicate will not be evaluated.
PredicateOrDemo.java
package com.concretepage;
import java.util.function.Predicate;
public class PredicateOrDemo {
  public static void main(String[] args) {
	Predicate<Student> isMaleStudent = s -> s.getAge() >= 20 && "male".equals(s.getGender());
	Predicate<Student> isFemaleStudent = s -> s.getAge() > 18 && "female".equals(s.getGender());
	Predicate<Student> isStudentPassed = s -> s.getMarks() >= 33;

	Student student1 = new Student("Mahesh", 22, "male", 35);
	//Test either male or female student
	Boolean result = isMaleStudent.or(isFemaleStudent).test(student1);
	System.out.println(result); //true
	//Is student passed, too
	result = isMaleStudent.or(isFemaleStudent).and(isStudentPassed).test(student1);
	System.out.println(result); //true
  }
} 
Output
true
true 

4. negate()

default Predicate<T> negate() 
negate is the default method of Predicate that returns a predicate that represents the logical negation of this predicate. If the result of evaluation is true, negate will make it false and if the result of evaluation is false, negate will make it true.
PredicateNegateDemo.java
package com.concretepage;
import java.util.function.Predicate;
public class PredicateNegateDemo {
  public static void main(String[] args) {
       Predicate<Integer> isNumberMatched = n -> n > 10 && n < 20;
       //With negate()
       Boolean result = isNumberMatched.negate().test(15);
       System.out.println(result); //false
       
       //Without negate()
       result = isNumberMatched.test(15);
       System.out.println(result); //true
       
       Predicate<String> isValidName = s -> s.length() > 5 && s.length() < 15;
       System.out.println(isValidName.negate().test("Krishna")); //false
       
       Predicate<Integer> isLessThan50 = n -> n < 50;
       System.out.println(isLessThan50.negate().test(60)); //true
       
       Predicate<Integer> isGreaterThan20 = n -> n > 20;
       System.out.println(isGreaterThan20.negate().test(30));  //false   
       
       result = isLessThan50.and(isGreaterThan20).negate().test(25);
       System.out.println(result); //false
  }
} 
Output
false
true
false
true
false
false 

5. isEqual(Object targetRef)

static <T> Predicate<T> isEqual(Object targetRef) 
isEqual is the static method of Predicate that returns the predicate that tests if two arguments are equal according to Objects.equals(Object, Object). We create predicate using Predicate.isEqual as following.
Predicate<String> isHelloMsg = Predicate.isEqual("Hello");
Predicate<Book> isMahabharatBook = Predicate.isEqual(new Book("Mahabharat", "Vyas")); 
Find the example.
PredicateIsEqualDemo.java
package com.concretepage;
import java.util.function.Predicate;
public class PredicateIsEqualDemo {
  public static void main(String[] args) {
    System.out.println("---Testing Hello message---");	
    Predicate<String> isHelloMsg = Predicate.isEqual("Hello");
    System.out.println(isHelloMsg.test("Hello")); //true
    System.out.println(isHelloMsg.test("Hi"));  //false
    
    System.out.println("---Testing Mahabharat book---");
    Book mahabharatBook = new Book("Mahabharat", "Vyas");
    Predicate<Book> isMahabharatBook = Predicate.isEqual(mahabharatBook);
    System.out.println(isMahabharatBook.test(new Book("Mahabharat", "Vyas"))); //true
    System.out.println(isMahabharatBook.test(new Book("Ramayan", "Valmiki"))); //true
  }
}

class Book {
  private String name;
  private String writer;
  public Book(String name, String writer) {
	this.name = name;
	this.writer = writer;
  }
  public String getName() {
    return name;
  }
  public String getWriter() {
    return writer;
  }
  public boolean equals(final Object obj) {
    if (obj == null) {
        return false;
    }
    final Book b = (Book) obj;
    if (this == b) {
        return true;
    } else {
        return (this.name.equals(b.name) && (this.writer == b.writer));
    }
  }  
} 
Output
---Testing Hello message---
true
false
---Testing Mahabharat book---
true
false 

6. not(Predicate<? super T> target)

static <T> Predicate<T> not(Predicate<? super T> target) 
not is the static method of Predicate introduced in Java 11. not returns predicate that is the negation of supplied predicate. This is accomplished by returning result of the calling target.negate(). Find the example of Predicate.not.
PredicateNotDemo.java
package com.concretepage;
import java.util.function.Predicate;
public class PredicateNotDemo {
  public static void main(String[] args) {
    Predicate<Integer> isOdd = n -> n % 2 == 1;
    Predicate<Integer> isEven = Predicate.not(isOdd);
    System.out.println(isEven.test(10)); //true
    
    Predicate<String> isNotHelloMsg = Predicate.not(Predicate.isEqual("Hello"));
    System.out.println(isNotHelloMsg.test("Hi")); //true
    System.out.println(isNotHelloMsg.test("Hello")); //false
  }
} 
Output
true
true
false 

Predicate with Stream

We will provide examples to use Predicate with Stream. We will filter list using Stream.filter. The syntax of filter() is as following.
filter(Predicate predicate) 
filter() returns the instance of Stream that consists the filtered data after processing given Predicate.
Example-1:
PredicateStreamDemo1.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class PredicateStreamDemo1 {
  public static void main(String[] args) {
	List<String> list = new ArrayList<>();	
	list.add("Vijay");
	list.add("Ramesh");
	list.add("Mahesh");
	
	Predicate<String> isNameEndsWithSh = s -> s.endsWith("sh");
	
	list.stream().filter(isNameEndsWithSh)
	  .forEach(s -> System.out.println(s));
  }
} 
Output
Ramesh
Mahesh 

Example-2:
PredicateStreamDemo2.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicateStreamDemo2 {
  public static void main(String[] args) {
	List<Student> list = new ArrayList<>();
	list.add(new Student("Mahesh", 20, "male", 38));
	list.add(new Student("Gauri", 21, "female", 45));	
	list.add(new Student("Krishna", 19, "male", 42));
	list.add(new Student("Radha", 20, "female", 35));
	
	System.out.println("--- All students scoring marks > 40 ---");
	Predicate<Student> isScoreGt40 = std -> std.getMarks() > 40;
	filterStudent(isScoreGt40, list).forEach(s -> System.out.println(s));
	
	System.out.println("--- All Male Students ---");
	Predicate<Student> isMaleStudent = std -> "male".equals(std.getGender());
	filterStudent(isMaleStudent, list).forEach(s -> System.out.println(s));
	
	System.out.println("--- All Female Students ---");
	Predicate<Student> isFemaleStudent = std -> "female".equals(std.getGender());
	filterStudent(isFemaleStudent, list).forEach(s -> System.out.println(s));	
	
	System.out.println("--- All Female Students scoring > 40 ---");
	filterStudent(isFemaleStudent.and(isScoreGt40), list).forEach(s -> System.out.println(s));		
  }
  
  static List<Student> filterStudent(Predicate<Student> predicate, List<Student> list) {
	return list.stream().filter(predicate).collect(Collectors.toList());
  }
} 
Output
--- All students scoring marks > 40 ---
Gauri - 21 - female - 45
Krishna - 19 - male - 42
--- All Male Students ---
Mahesh - 20 - male - 38
Krishna - 19 - male - 42
--- All Female Students ---
Gauri - 21 - female - 45
Radha - 20 - female - 35
--- All Female Students scoring > 40 ---
Gauri - 21 - female - 45 

Reference

Interface Predicate
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us