Java 8 — Predicate | Code Factory

Code Factory
7 min readMay 4, 2020

--

Index Page : Link

Reference Link : Link

Donate : Link

  • A Predicate is a function with a single argument and returns boolean value.
  • To implement Predicate functions in Java, Oracle people introduced Predicate interface in 1.8 version (i.e. Predicate<T>).
  • Predicate interface present in java.util.function package.
  • It’s a functional interface and it contains only one method i.e., test()
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t); // abstract
default Predicate<T> and(Predicate<? super T> other); // default
default Predicate<T> negate(); // default
default Predicate<T> or(Predicate<? super T> other); // default
static <T> Predicate<T> isEqual(Object targetRef); // static
}
  • As Predicate is a functional interface and hence it can refers Lambda (λ) Expression.

Converting normal method to predicate :

public boolean test(Integer i) {
if(i > 10) {
return true;
} else {
return false;
}
}
||
(Integer i) -> {
if(i > 10) {
return true;
} else {
return false;
}
};
||
i -> (i > 10); ||
Predicate<Integer> p = i -> i > 10;
System.out.println(p.test(20));
System.out.println(p.test(8));
package com.codeFactory.predicate;import java.util.function.Predicate;public class Test {
public static void main(String... args) {
Predicate<Integer> p = i -> i > 10;
System.out.println(p.test(20)); // ✓
System.out.println(p.test(8)); // ✓
System.out.println(p.test("Code Factory")); // X
}
}

CE : incompatible types: String cannot be converted to Integer

Write a predicate to check the length of given string is greater than 3 or not :

package com.codeFactory.predicate;import java.util.function.Predicate;public class Test {
public static void main(String... args) {
Predicate<String> p = s -> s.length() > 5;
System.out.println(p.test("Code")); // false
System.out.println(p.test("Factory")); // true
}
}

write a predicate to check whether the given collection is empty or not :

package com.codeFactory.predicate;import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
public class Test {
public static void main(String... args) {
Predicate<Collection> p = c -> c.isEmpty();

List<String> l = new ArrayList<String>();
System.out.println(p.test(l)); // true

Set<Integer> s = new HashSet<Integer>();
s.add(5);
System.out.println(p.test(s)); // false
}
}

Predicate Joining :

It’s possible to join predicates into a single predicate by using the following methods.

  1. and()
  2. or()
  3. negate()

These are exactly same as logical AND, OR, complement operators

package com.codeFactory.predicate;import java.util.function.Predicate;public class Test {
public static void main(String... args) {
int x[] = {0, 1, 2, 3, 4, 5, 6};
Predicate<Integer> p1 = i -> i > 3;
Predicate<Integer> p2 = i -> i%2 == 0;
System.out.println("Numbers greater than 3 :");
m1(p1, x);
System.out.println("Even numbers :");
m1(p2, x);
System.out.println("Numbers not greater than 3 :");
m1(p1.negate(), x);
System.out.println("Numbers greater than 3 and even are :");
m1(p1.and(p2), x);
System.out.println("Numbers greater than 3 or even are :");
m1(p1.or(p2), x);
}

private static void m1(Predicate<Integer> p, int x[]) {
for(int i : x) {
if(p.test(i)) {
System.out.println(i);
}
}
}
}

Output :

Numbers greater than 3 :
4
5
6
Even numbers :
0
2
4
6
Numbers not greater than 3 :
0
1
2
3
Numbers greater than 3 and even are :
4
6
Numbers greater than 3 or even are :
0
2
4
5
6

Program to display names starts with ’N’ by using Predicate :

package com.codeFactory.predicate;import java.util.function.Predicate;public class Test {
public static void main(String... args) {
String names[] = {"Narendra", "Amit", "Narayan", "Vijay", "Nitin"};
Predicate<String> p = s -> s.startsWith("N");
System.out.println("Names start with N are :");
for(String s : names) {
if(p.test(s)) {
System.out.println(s);
}
}
}
}

Output :

Names start with N are :
Narendra
Narayan
Nitin

Predicate Example to remove null values and empty strings from the given array :

package com.codeFactory.predicate;import java.util.function.Predicate;public class Test {
public static void main(String... args) {
String names[] = {"Narendra", "Amit", "", null, "Nitin"};
Predicate<String> p = s -> s != null && s.trim().length() > 0;
System.out.println("Names :");
for(String s : names) {
if(p.test(s)) {
System.out.println(s);
}
}
}
}

Output :

Names :
Narendra
Amit
Nitin

Program for User Authentication by using Predicate :

package com.codeFactory.predicate;import java.util.Scanner;
import java.util.function.Predicate;
class User {
String username;
String psw;
User(String username, String psw) {
this.username = username;
this.psw = psw;
}
}
public class Test {
public static void main(String... args) {
Predicate<User> p = u -> u.username.equals("code") && u.psw.equals("factory");
Scanner sc = new Scanner(System.in);
System.out.println("Enter Username : ");
String username = sc.next();
System.out.println("Enter Password : ");
String psw = sc.next();
User user = new User(username, psw);
if(p.test(user)) {
System.out.println("Valid user");
} else {
System.out.println("Not valid user");
}

}
}

Output :

Enter Username : 
code
Enter Password :
factory
Valid user

Employee Management Application :

package com.codeFactory.predicate;import java.util.ArrayList;
import java.util.function.Predicate;
class Employee {
String name;
String designation;
double salary;
String city;

Employee(String name, String designation, double salary, String city) {
this.name = name;
this.designation = designation;
this.salary = salary;
this.city = city;
}
@Override
public String toString() {
return "Employee [name=" + name + ", designation=" + designation
+ ", salary=" + salary + ", city=" + city + "]";
}
@Override
public boolean equals(Object obj) {
Employee e = (Employee)obj;
if(name.equals(e.name) && designation.equals(e.designation) && salary == e.salary && city.equals(e.city)) {
return true;
} else {
return false;
}
}
}public class Test {
public static void main(String... args) {
ArrayList<Employee> list = new ArrayList<Employee>();
populate(list);

Predicate<Employee> p1 = e -> e.designation.equals("Manager");
System.out.println("Manager Info : ");
display(p1, list);

Predicate<Employee> p2 = e -> e.city.equals("Gandhinagar");
System.out.println("Gandhinagar employees Info : ");
display(p2, list);

Predicate<Employee> p3 = e -> e.salary < 20000;
System.out.println("Employees salary < 20000 Info : ");
display(p3, list);

System.out.println("All Managers from Gandhinagar city : ");
display(p1.and(p2), list);

System.out.println("Managers or salary < 20000");
display(p1.or(p3), list);

System.out.println("Not Managers : ");
display(p1.negate(), list);

Predicate<Employee> isCEO = Predicate.isEqual(new Employee("Narendra", "CEO", 30000, "Ahmedabad"));

Employee e1 = new Employee("Narendra", "CEO", 30000, "Ahmedabad");
Employee e2 = new Employee("Amit", "Manager", 20000, "Ahmedabad");
System.out.println(isCEO.test(e1));
System.out.println(isCEO.test(e2));

}

private static void populate(ArrayList<Employee> list) {
list.add(new Employee("Narendra", "CEO", 30000, "Ahmedabad"));
list.add(new Employee("Amit", "Manager", 20000, "Ahmedabad"));
list.add(new Employee("Vijay", "Manager", 20000, "Gandhinagar"));
list.add(new Employee("Nitin", "Lead", 15000, "Ahmedabad"));
list.add(new Employee("Aanandi", "Lead", 15000, "Gandhinagar"));
list.add(new Employee("Asok", "Developer", 10000, "Ahmedabad"));
list.add(new Employee("Rahul", "Developer", 10000, "Ahmedabad"));
list.add(new Employee("Narayan", "Developer", 10000, "Gandhinagar"));
}

private static void display(Predicate<Employee> p, ArrayList<Employee> list) {
for(Employee e : list) {
if(p.test(e)) {
System.out.println(e);
}
}
System.out.println();
}
}

Output :

Manager Info : 
Employee [name=Amit, designation=Manager, salary=20000.0, city=Ahmedabad]
Employee [name=Vijay, designation=Manager, salary=20000.0, city=Gandhinagar]
Gandhinagar employees Info :
Employee [name=Vijay, designation=Manager, salary=20000.0, city=Gandhinagar]
Employee [name=Aanandi, designation=Lead, salary=15000.0, city=Gandhinagar]
Employee [name=Narayan, designation=Developer, salary=10000.0, city=Gandhinagar]
Employees salary < 20000 Info :
Employee [name=Nitin, designation=Lead, salary=15000.0, city=Ahmedabad]
Employee [name=Aanandi, designation=Lead, salary=15000.0, city=Gandhinagar]
Employee [name=Asok, designation=Developer, salary=10000.0, city=Ahmedabad]
Employee [name=Rahul, designation=Developer, salary=10000.0, city=Ahmedabad]
Employee [name=Narayan, designation=Developer, salary=10000.0, city=Gandhinagar]
All Managers from Gandhinagar city :
Employee [name=Vijay, designation=Manager, salary=20000.0, city=Gandhinagar]
Managers or salary < 20000
Employee [name=Amit, designation=Manager, salary=20000.0, city=Ahmedabad]
Employee [name=Vijay, designation=Manager, salary=20000.0, city=Gandhinagar]
Employee [name=Nitin, designation=Lead, salary=15000.0, city=Ahmedabad]
Employee [name=Aanandi, designation=Lead, salary=15000.0, city=Gandhinagar]
Employee [name=Asok, designation=Developer, salary=10000.0, city=Ahmedabad]
Employee [name=Rahul, designation=Developer, salary=10000.0, city=Ahmedabad]
Employee [name=Narayan, designation=Developer, salary=10000.0, city=Gandhinagar]
Not Managers :
Employee [name=Narendra, designation=CEO, salary=30000.0, city=Ahmedabad]
Employee [name=Nitin, designation=Lead, salary=15000.0, city=Ahmedabad]
Employee [name=Aanandi, designation=Lead, salary=15000.0, city=Gandhinagar]
Employee [name=Asok, designation=Developer, salary=10000.0, city=Ahmedabad]
Employee [name=Rahul, designation=Developer, salary=10000.0, city=Ahmedabad]
Employee [name=Narayan, designation=Developer, salary=10000.0, city=Gandhinagar]
true
false

Predicate interface isEqual() method :

package com.codeFactory.predicate;import java.util.function.Predicate;public class Test1 {
public static void main(String... args) {
Predicate<String> p = Predicate.isEqual("Code Factory");
System.out.println(p.test("CODE FACTORY")); // false
System.out.println(p.test("Code Factory")); // true
}
}
  • To check whether the given element equal to element represented by Predicate or not.

Predicate Practice Bits :

(1) Which of the following abstract method present in Predicate interface?

A. test()     ✓
B. apply()
C. get()
D. accept()
Explanation : Predicate functional interface contains only one abstract method : test()

(2) Which of the following is the static method present in Predicate interface?

A. test()
B. and()
C. or()
D. isEqual() ✓
Explanation : Predicate functional interface contains only one static method : isEqual()

(3) Which of the following default methods present in Predicate interface?

A. and()
B. or()
C. negate()
D. All the above ✓
Explanation : Predicate Functional interface contains the following 3 default methods : and(), or(), not()

(4) Which of the following is Predicate interface declaration?

A.     ✓
interface Predicate<T> {
public boolean test(T t);
}
B.
interface Predicate<T> {
public boolean apply(T t);
}
C.
interface Predicate<T, R> {
public R test(T t);
}
D.
interface Predicate<T, R> {
public R apply(T t);
}
Explanation :
interface Predicate<T> {
public boolean test(T t);
}
Predicate interface can take only one Type parameter which represents only input type. We are not required to specify return type because return type is always boolean type.

(5) Which of the following is valid Predicate to check whether the given Integer is divisible by 10 or not?

A. Predicate<Integer> p = i -> i%10 == 10;     ✓
B. Predicate<Integer,Boolean> p = i -> i%10 == 0;
C. Predicate<Boolean,Integer> p = i -> i%10 == 0;
D. None of the above
Explanation :
interface Predicate<T> {
public boolean test(T t);
}
Predicate interface can take only one Type parameter which represents only input type. We are not required to specify return type because return type is always boolean type

(6) Which of the following is valid regarding Predicate functional interface?

A. Predicate Functional interface present in java.util.function package
B. It is introduced in java 1.8 version
C. We can use Predicate to implement conditional checks
D. It is possible to join 2 predicates into a single predicate also
E. All the above ✓

(7) Which of the following is valid Predicate to check whether the given user is admin or not?

A. Predicate<User> p = user -> user.getRole().equals("Admin");     ✓
B. Predicate<Boolean> p = user -> user.getRole().equals("Admin");
C. Predicate<User> p = (user,s="admin") -> user.getRole().equals(s);
D. None of the above
Explanation :
interface Predicate<T> {
public boolean test(T t);
}
Predicate interface can take only one Type parameter which represents only input type. We are not required to specify return type because return type is always boolean type

(8) Consider the following Predicates

Predicate<Integer> p1 = i -> i%2 == 0;
Predicate<Integer> p1 = i -> i > 10;
Which of the following are invalid ?
A. p1.and(p2)
B. p1.or(p2)
C. p1.negate(p2) ✓
D. p1.negate()
Explanation : negate() method won't take any argument

--

--