What is Predicate Functional Interface in Java 8

Predicate in Java 8

The Predicate is one of the Functional Interfaces type introduced in Java 8. Generally predicate means a statement that determines if a value could be true or false.
So predicate is used to test a condition which will return a boolean value.

Syntax:

@FunctionalInterface
public interface Predicate {
	boolean test(T t);
}

Use cases where Predicate can be used:
1) Filtering a set of objects in stream.
2) Sorting list by data validation

Example:

import java.util.function.Predicate;
public class TestPredicate {
    public static void main(String[] args) {
        // Defining predicate
        Predicate lessThanPredicate = i -> (i < 50);
        // Calling Predicate defined above
        System.out.println("Age 10 is less than 50:" + lessThanPredicate.test(10));
    }
}

Using Filter example:

import java.util.List;
import java.util.function.Predicate;
public class TestPredicate {
    public static void main(String[] args) {
        // Defining predicate
        Predicate minorAgePredicate = i -> (i < 18);
        List allAgeList = List.of(16, 28, 49, 36, 30, 40, 89, 6, 5, 19, 45, 13);
        System.out.println("Age of minors are below:");
        allAgeList.stream().filter(minorAgePredicate).forEach(System.out::println);
    }
}

Leave a comment