Java 8 – Predicate Functional Interface

In this article, we will discuss one of the widely used pre-defined Functional Interface in Java 1.8 version for conditional checks i.e.; Predicate Functional Interface

1. Predicate Functional Interface:

  • This Functional Interface has one abstract method called test(T t); which
    • Step 1 :- accepts 1 input argument of any data-type
    • Step 2 :- performs some conditional checks to evaluate result
    • Step 3 :- And always returns result as Boolean value either as true/false
  • Below is interface Predicate containing test(); method along with other default & static methods

Predicate.java

package java.util.function;

import java.util.Objects;

@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);
    
    // other default and static methods
}

2. Examples for Predicate Functional Interface :

2.1 To evaluate whether given number is odd/even :

TestEvenOdd.java

package net.bench.resources.predicate.example;

import java.util.function.Predicate;

public class TestEvenOdd {

	public static void main(String[] args) {

		// lambda expression to evaluate number is EVEN using Predicate FI
		Predicate<Integer> p = i -> i%2 == 0;

		// testing number using Predicate
		System.out.println("1. Whether number 10 is even/odd \t: " + p.test(10));

		System.out.println("2. Whether number 5 is even/odd \t: " + p.test(5));

		System.out.println("3. Whether number 1992 is even/odd \t: " + p.test(1992));

		System.out.println("4. Whether number 9753 is even/odd \t: " + p.test(9753));

		System.out.println("5. Whether number 2020 is even/odd \t: " + p.test(10));
	}
}

Output:

1. Whether number 10 is even/odd 	: true
2. Whether number 5 is even/odd 	: false
3. Whether number 1992 is even/odd 	: true
4. Whether number 9753 is even/odd 	: false
5. Whether number 2020 is even/odd 	: true

2.2 To check whether given String length is greater than 7 :

TestStringLength.java

package net.bench.resources.predicate.example;

import java.util.function.Predicate;

public class TestStringLength {

	public static void main(String[] args) {

		// lambda expression to evaluate String length is greater than 7 using Predicate FI
		Predicate<String> p = s -> s.length() > 7;

		// testing number using Predicate
		System.out.println("1. Whether 'BenchResources' contains length > 7 : " 
				+ p.test("BenchResources"));

		System.out.println("2. Whether 'Java 8' contains length > 7 \t: " 
				+ p.test("Java 8"));

		System.out.println("3. Whether 'Anushka' contains length > 7 \t: " 
				+ p.test("Anushka"));

		System.out.println("4. Whether 'Tendulkar' contains length > 7 \t: " 
				+ p.test("Tendulkar"));

		System.out.println("5. Whether 'Madhavan' contains length > 7 \t: " 
				+ p.test("Madhavan"));
	}
}

Output:

1. Whether 'BenchResources' contains length > 7 : true
2. Whether 'Java 8' contains length > 7 	: false
3. Whether 'Anushka' contains length > 7 	: false
4. Whether 'Tendulkar' contains length > 7 	: true
5. Whether 'Madhavan' contains length > 7 	: true

2.3 To check whether given names starts with capital letter R :

TestNameStarting.java

package net.bench.resources.predicate.example;

import java.util.function.Predicate;

public class TestNameStarting {

	public static void main(String[] args) {

		// lambda expression to evaluate check name starts with 'R' using Predicate FI
		Predicate<String> p = s -> s.startsWith("R");

		String[] names = {
				"Virat Kohli",
				"Rohit Sharma",
				"Ravindra Jadeja",
				"Jasprit Bumrah",
				"Lokesh Rahul",
				"Hardik Pandya",
				"Rishabh Pant"
		};

		// testing number using Predicate
		for(String name : names) {
			System.out.println("Whether '" + name + "' starts with 'R' : \t" 
					+ p.test(name));
		}
	}
}

Output:

Whether 'Virat Kohli' starts with 'R' : 	false
Whether 'Rohit Sharma' starts with 'R' : 	true
Whether 'Ravindra Jadeja' starts with 'R' : 	true
Whether 'Jasprit Bumrah' starts with 'R' : 	false
Whether 'Lokesh Rahul' starts with 'R' : 	false
Whether 'Hardik Pandya' starts with 'R' : 	false
Whether 'Rishabh Pant' starts with 'R' : 	true

2.4 To check whether employee salary is more than 10,000 :

TestEmployeeSalary.java

package net.bench.resources.predicate.example;

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

class Employee {

	// member variables
	String name;
	int salary;

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


public class TestEmployeeSalary {

	public static void main(String[] args) {

		// Creating ArrayList of Employee
		List<Employee> employees = new ArrayList<>();

		// adding few employees to list
		employees.add(new Employee("Arjun", 16500));
		employees.add(new Employee("Nambi", 5600));
		employees.add(new Employee("Sankar", 90500));
		employees.add(new Employee("Vineet", 9700));
		employees.add(new Employee("Madhu", 10500));

		// lambda expression to check employee salary is greater than 10000 using Predicate FI
		Predicate<Employee> p = emp -> emp.salary > 10000;

		// testing number using Predicate
		for(Employee employee : employees) {
			System.out.println("Whether '" + employee.name + "' has salary more than 10000 : \t" 
					+ p.test(employee));
		}
	}
}

Output:

Whether 'Arjun' has salary more than 10000 : 	true
Whether 'Nambi' has salary more than 10000 : 	false
Whether 'Sankar' has salary more than 10000 : 	true
Whether 'Vineet' has salary more than 10000 : 	false
Whether 'Madhu' has salary more than 10000 : 	true

3. Predicate Joining :

  • When we want to combine 2 or more predicates into one, then it is called as Predicate Joining
  • We can do 2 different types of predicate joining i.e.;
  • and” predicate :- If both combining predicates evaluates to true, then final predicate result also be true; otherwise false
  • or” predicate :- If either of the combining predicates evaluates to true, then final predicate result also be true; otherwise false (kind of short-circuit operation)
  • We will look at example for each case separately

3.1 and Predicate :

  • 1st Predicate evaluates whether number is even (or odd)
  • 2nd Predicate evaluates whether that same number is greater than 35
  • We are using and predicate and if both predicates evaluates to true only then it will be true; otherwise it is false

TestAndPredicate.java

package net.bench.resources.predicate.example;

import java.util.function.Predicate;

public class TestAndPredicate {

	public static void main(String[] args) {

		// 1- lambda expression to evaluate number is EVEN using Predicate FI
		Predicate<Integer> p1 = i -> i%2 == 0;

		// 1- lambda expression to evaluate number is greater than 35 using Predicate FI
		Predicate<Integer> p2 = i -> i > 35;

		// set of numbers for our demo
		int numbers[] = {25, 35, 50, 60, 75, 90, 100};

		// iterate and check both predicates
		for(int num : numbers) {

			if(p1.and(p2).test(num)) {
				System.out.println(num + " is EVEN as well as greater than 35");
			}
		}
	}
}

Output:

50 is EVEN as well as greater than 35
60 is EVEN as well as greater than 35
90 is EVEN as well as greater than 35
100 is EVEN as well as greater than 35

3.2 or Predicate :

  • 1st Predicate evaluates whether number is even (or odd)
  • 2nd Predicate evaluates whether that same number is greater than 35
  • We are using or predicate to check either of the predicates evaluates true then final result is true; otherwise it is false

TestOrPredicate.java

package net.bench.resources.predicate.example;

import java.util.function.Predicate;

public class TestOrPredicate {

	public static void main(String[] args) {

		// 1- lambda expression to evaluate number is EVEN / ODD using Predicate FI
		Predicate<Integer> p1 = i -> i%2 == 0;

		// 1- lambda expression to evaluate number is greater than 35 using Predicate FI
		Predicate<Integer> p2 = i -> i > 35;

		// set of numbers for our demo
		int numbers[] = {25, 35, 50, 60, 75, 90, 99};

		// iterate and check whether one of the predicates evaluates true
		for(int num : numbers) {

			if(p1.or(p2).test(num)) {
				System.out.println(num + " is either EVEN or greater than 35");
			}
		}
	}
}

Output:

50 is either EVEN or greater than 35
60 is either EVEN or greater than 35
75 is either EVEN or greater than 35
90 is either EVEN or greater than 35
99 is either EVEN or greater than 35

3.3 negate Predicate :

  • negate predicate return result in negative i.e.; if predicate evaluates to true then negate predicate return result as false
  • Basically, opposite of whatever it evaluates
  • Although, lambda expression evaluates true for EVEN number but here negate() evaluating to false

TestNegatePredicate.java

package net.bench.resources.predicate.example;

import java.util.function.Predicate;

public class TestNegatePredicate {

	public static void main(String[] args) {

		// lambda expression to evaluate number is EVEN using Predicate FI
		Predicate<Integer> p = i -> i%2 == 0;

		// set of numbers for our demo
		int numbers[] = {23, 36, 51, 66, 78, 90, 97};

		// iterate and evaluate numbers
		for(int num : numbers) {
                        // checking numbers are ODD
			if(p.negate().test(num)) {
				System.out.println(num + " is ODD number");
			}
		}
	}
}

Output:

23 is ODD number
51 is ODD number
97 is ODD number

Related Articles :

References :

Happy Coding !!
Happy Learning !!

Java 8 - Function Functional Interface
Java 8 - Pre-defined Functional interface