Predicate accepts an argument and returns a boolean value. Predicate functional interface in Java is a type of function that accepts a single argument and returns a boolean (True/ False). It provides the functionality of filtering, it filter a stream components on the base of a provided predicate.
public static void main(String[] args) { Predicate<
Integer
> pr = a -> (a > 10); // Calling Predicate method System.out.println(pr.test(20));
} Output: true
public static void main(String[] args) { Predicate<
String> pr = Predicate.isEqual( "MyAllText" ); // Calling Predicate method System.out.println( pr.test("AllText") ); // Calling Predicate method System.out.println( pr.test("MyAllText") ); // Calling Predicate method System.out.println( pr.test("MyAll") ); } Output: false true false
public static void main(String[] args)
{
Predicate<Integer> pr1 = x -> (x > 20); Predicate<
Integer> pr2 = x -> (x < 80); // Calling Predicate method System.out.println( pr1.and(pr2).test(100) ); // Calling Predicate method System.out.println( pr1.and(pr2).test(50) ); // Calling Predicate method System.out.println( pr1.and(pr2).test(10) ); } Output: false true false
public static void main (
String[] args) {
Predicate<String> startsWithCharJ = s -> s.startsWith("H"); Predicate<
String> hasLengthOfInt5 = s -> s.length() == 5; // Calling without negate method System.out.println( startsWithCharJ.test("Horse") ); // Calling without negate method System.out.println( hasLengthOfInt5 .test("India") ); Predicate<
String> negateStartsWithCharJ = startsWithCharJ.negate(); Predicate
<String> negatehasLengthOfInt5 = hasLengthOfInt5.negate(); // Calling after negate predicate System.out.println( negateStartsWithCharJ .test("Horse") ); // Calling after negate predicate System.out.println( negatehasLengthOfInt5 .test("India") ); } Output: true true false false
public static void main (
String
[] args) {
Predicate<String
> startsWithCharH = s -> s.startsWith( "H" ); Predicate<
String
> hasLengthOfInt5 = s -> s.length() == 5; Predicate<
String
> startsWithCharHOrHasLengthOf5 = startsWithCharH.or(hasLengthOfInt5); System.out.println( startsWithCharHOrHasLengthOf5 .test( "Hero" ) ); System.out.println( startsWithCharHOrHasLengthOf5 .test( "India" ) ); System.out.println( startsWithCharHOrHasLengthOf5 .test( "Method" ) ); } Output: true true false
Bi-Predicate is also an extension of the Predicate functional interface, which, instead of one, takes two arguments, does some processing, and returns the boolean value.