Predicates

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). Predicate interface present in java.util.function package. It’s a functional interface and it contains only one method.


As predicate is a functional interface and hence it can refers lambda expression.

Q.Write a predicate to check whether the given integer is greater than 10 or not.

Program:

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

Predicate p = s (s.length() > 3);
System.out.println(p.test(“testData”)); true
System.out.println(p.test(“test”)); false

Q.Write a predicate to check whether the given collection is empty or not.
Predicate p = c —> c.isEmpty();

Predicate joining-

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

and()
or()
negate()

these are exactly same as logical AND ,OR complement operators.


Java 8 Features Functions