๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Predicate Interface  


Introduction
  • Predicate interface is a functional interface in Java 8 that represents a boolean-valued function (a condition or test) of one argument.
  • It is part of the java.util.function package.
  • Uses of Predicate Interface:
    • Used to test conditions on objects.
    • Used to filter elements in collections.
    • Can combine multiple conditions using and(), or(), and negate().
    • Helps write clean, functional-style code using lambda expressions.
  • Syntax :
    public interface Predicate
    {
        boolean test(T t);
        //some default methods are also present
    }
Programs:
  • 1. Simple program without lambda expression:
    import java.util.function.Predicate;
    
    public class MainApp
    {
        public static void main(String[] args)
        {
            // Predicate to check if a number is even using anonymous class
            Predicate<Integer> isEven = new Predicate<Integer>() {
                @Override
                public boolean test(Integer x) {
                    return x % 2 == 0;
                }
            };
    
            // Test numbers
            System.out.println("Is 4 is even : " + isEven.test(4));
            System.out.println("Is 7 is even : " + isEven.test(7));
        }
    }
  • 2. Program with lambda expression:
    import java.util.function.Predicate;
    
    public class MainApp
    {
        public static void main(String[] args)
        {
            // Predicate to check if a number is even using lambda expression
            Predicate<Integer> isEven = x -> x % 2 == 0;
    
            // Test numbers
            System.out.println("Is 4 even? " + isEven.test(4));
            System.out.println("Is 7 even? " + isEven.test(7));
        }
    }