DEV Community

Cover image for Part-2 Why Functional Interfaces Matter in Java 8(Predicate)
s mathavi
s mathavi

Posted on

Part-2 Why Functional Interfaces Matter in Java 8(Predicate)

Now we will discussed about the part2 of Functional Interface.

1.Predicate:

  • A Predicate is a functional interface in Java (java.util.function.Predicate<T>).
  • It has exactly one abstract method:
@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}
Enter fullscreen mode Exit fullscreen mode
  • Input: one value of type T
  • Output: true or false
  • Purpose: Used for condition checking.

Basic Example:

import java.util.function.Predicate;

public class PredicateDemo {
    public static void main(String[] args) {
        Predicate<Integer> isEven = n -> n % 2 == 0;

        System.out.println(isEven.test(10)); // true
        System.out.println(isEven.test(7));  // false
    }
}

Enter fullscreen mode Exit fullscreen mode

Predicate Chaining

Predicates can be combined:
-and() → both conditions must be true
-or() → at least one condition must be true
-negate() → opposite of condition

Example: Employee Age and Salary

class Employee {
    String name;
    int age;
    double salary;
    Employee(String n, int a, double s) { name = n; age = a; salary = s; }
}

Predicate<Employee> isAdult = e -> e.age > 18;
Predicate<Employee> highSalary = e -> e.salary > 50000;

Predicate<Employee> eligible = isAdult.and(highSalary);

System.out.println(eligible.test(new Employee("Ravi", 25, 60000))); // true
System.out.println(eligible.test(new Employee("Anu", 17, 70000)));  // false
Enter fullscreen mode Exit fullscreen mode

Negate Condition


Predicate<Integer> isEven = n -> n % 2 == 0;
Predicate<Integer> isOdd = isEven.negate();

System.out.println(isOdd.test(5)); // true
System.out.println(isOdd.test(8)); // false
Enter fullscreen mode Exit fullscreen mode

Negate turns even check → odd check.


We’ll continue exploring more Java concepts in the next blog. See you soon!

Top comments (0)