Java 8 Predicate examples
Predicate
is single argument functional interface which returns true or false. It takes one argument and returns result in form of true or false.
// Using anonymous class Predicate<Integer> predicate=new Predicate<Integer>() { @Override public boolean test(Integer i) { return i > 100; } }; // Using lambda expression Predicate<Integer> predicate = i -> i > 100; |
Here is the definition of Predicate
interface.
package java.util.function; import java.util.Objects; /** * * Represents a predicate (boolean-valued function) of one argument. * * * <p> * This is a <a href=”package-summary.html”>functional interface</a> * whose * functional method is {@link #test(Object)}. * * @param <T> the type of the * input to the predicate * * @since 1.8 */ @FunctionalInterfacepublic 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); default Predicate<T> and(Predicate<? super T> other) { Objects.requireNonNull(other); return (t) -> test(t) && other.test(t); } default Predicate<T> negate() { return (t) -> !test(t); } default Predicate<T> or(Predicate<? super T> other) { Objects.requireNonNull(other); return (t) -> test(t) || other.test(t); } static <T> Predicate<T> isEqual(Object targetRef) { return (null == targetRef) ? Objects::isNull : object -> targetRef.equals(object); } } |
Predicate methods example
test()
This is abstract method of Predicate interface. It evaluates true if predicate matches the input argument.
Here is simple example of test()
method which checks if input argument is greater than 100 or not.
import java.util.function.Predicate; public class Java8PredicateExample { public static void main(String[] args) { Predicate<Integer> predicate = i -> i > 100; boolean greaterCheck = predicate.test(200); System.out.println(“is 200 greater than 100: ” + greaterCheck); } } |
Output:is 200 greater than 100: true
You can pass Predicate as a function argument too.
import java.util.function.Predicate; public class Java8PredicateMethodExample { public static void main(String[] args) { boolean greaterCheckBoolean = greaterCheck(200, p -> p > 100); System.out.println(greaterCheckBoolean); } public static boolean greaterCheck(int number, Predicate<Integer> predicate) { return predicate.test(number); } } |
and()
and() is default method which returns composite predicate that denotes logical AND of this predicate and passed predicate.
mport java.util.function.Predicate; public class Java8PredicateAndExample { public static void main(String[] args) { Predicate<Integer> predicate1 = i -> i > 100; Predicate<Integer> predicate2 = i -> i < 300; Predicate<Integer> andPredicate = predicate1.and(predicate2); boolean rangeCheck = andPredicate.test(200); System.out.println(“200 lies between 100 and 300: ” + rangeCheck); } } |
Output:200 lies between 100 and 300: true
We have created two predicates and checked logical AND between predicate1 and predicate2
or()
or() is default method which returns composite predicate that denotes logical OR of this predicate and passed predicate.
import java.util.function.Predicate; public class Java8PredicateAndExample { public static void main(String[] args) { Predicate<Integer> predicate1 = i -> i > 100; Predicate<Integer> predicate2 = i -> i < 50; Predicate<Integer> andPredicate = predicate1.or(predicate2); boolean rangeCheck = andPredicate.test(30); System.out.println(“(30 > 100) or (30 < 50) returns: ” + rangeCheck); } } |
Output:(30 > 100) or (30 < 50) returns: true
We have created two predicates and checked logical or between predicate1 and predicate2
negate()
negate() is default method which returns predicate that denotes logical negation of this predicate.
import java.util.function.Predicate; public class Java8PredicateAndExample { public static void main(String[] args) { Predicate<Integer> predicate = i -> i > 100; Predicate<Integer> NegatePredicate = predicate.negate(); // Negate predicate will become i -> i < 100 boolean // rangeCheck = NegatePredicate.test(30); // System.out.println(“30 is less than 100: “+ // rangeCheck); }} } } |
Output:30 is less than 100: true
We have created two predicates and checked logical or between predicate1 and predicate2
isEqual()
isEqual() is static method returns predicate that compares if two arguments are equal based on object’s equals() method.
import java.util.function.Predicate; public class Java8PredicateAndExample { public static void main(String[] args) { Predicate<String> predicate = Predicate.isEqual(“test1”); System.out.println(predicate.test(“test1”)); System.out.println(predicate.test(“test2”)); } } |
Output:true
false
predicate.test("test1")
returnstrue
because it matches with"test1"
passed to isEqual methodpredicate.test("test2")
returnsfalse
because it does not match with"test1"
passed to isEqual method
Please note that above comparison is done on the basis of String’s equals()
method.
Filter list using Predicate
Java 8 stream’s filter
method takes Predicate
as a argument and can be used to filter the list with the help of predicates.
Lets say you have student class as below:
public class Student { private int id; private String name; private String gender; private int age; public Student(int id, String name, String gender, int age) { super(); this.id = id; this.name = name; this.gender = gender; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return “Student [id=” + id + “, name=” + name + “, gender=” + gender + “, age=” + age + “]”; } } |
Lets create a function which will be used to filter students based on predicates.
public static List filterStudents (List students,Predicate predicate) { return students.stream().filter( predicate).collect(Collectors.toList()); } |
Lets create a main class as below:
import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; public class Java8PredicateStudentExample { public static void main(String[] args) { List<Student> studentList = createStudentList(); // Filter all male student who have age > 18 Predicate<Student> predicate1 = s -> s.getGender().equalsIgnoreCase(“M”) && s.getAge() > 18; List<Student> students1 = filterStudents(studentList, predicate1); System.out.println(“Male students having age > 18 are :” + students1); // Filer all female student who have age < 18 Predicate<Student> predicate2 = s -> s.getGender().equalsIgnoreCase(“F”) && s.getAge() < 18; List<Student> students2 = filterStudents(studentList, predicate2); System.out.println(“Female students having age < 18 are :” + students2); } public static List<Student> filterStudents(List<Student> students, Predicate<Student> predicate) { return students.stream().filter(predicate).collect(Collectors.toList()); } public static List<Student> createStudentList() { List<Student> studentList = new ArrayList<>(); Student s1 = new Student(1, “Arpit”, “M”, 19); Student s2 = new Student(2, “John”, “M”, 17); Student s3 = new Student(3, “Mary”, “F”, 14); Student s4 = new Student(4, “Martin”, “M”, 21); Student s5 = new Student(5, “Monica”, “F”, 16); Student s6 = new Student(6, “Ally”, “F”, 20); studentList.add(s1); studentList.add(s2); studentList.add(s3); studentList.add(s4); studentList.add(s5); studentList.add(s6); return studentList; } } |
When you run above program, you will get below output:18 are :[Student [id=1, name=Arpit, gender=M, age=19], Student [id=4, name=Martin, gender=M, age=21]]
Female students having age < 18 are :[Student [id=3, name=Mary, gender=F, age=14], Student [id=5, name=Monica, gender=F, age=16]]
That’s all about Java 8 Predicate example