Importance of Predicate interface in lambda expression in Java?



Predicate<T> is a generic functional interface that represents a single argument function that returns a boolean value (true or false). This interface available in java.util.function package and contains a test(T t) method that evaluates the predicate of a given argument.

Syntax

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

Example

import java.util.*; import java.util.functionPredicate; public class LambdaPredicateTest {    public static void main(String args[]) {       Employee emp1 = new Employee("Raja", 26);       Employee emp2 = new Employee("Jaidev", 24);       Employee emp3 = new Employee("Adithya", 30);       List<Employee> empList = new ArrayList<Employee>();       empList.add(emp1);       empList.add(emp2);       empList.add(emp3);       Predicate<Employee> predicateForAge = (e) -> e.age >= 25;       Predicate<Employee> predicateForName = (e) -> e.name.startsWith("A");       for(Employee emp : empList) {          if(predicateForAge.test(emp)) {             System.out.println(emp.name +" is eligible by age");          }       }       System.out.println("----------------------------");       for(Employee emp : empList) {          if(predicateForName.test(emp)) {             System.out.println(emp.name +" is eligible by name");          }       }    } } // Employee class class Employee {    public String name;    public int age;    public Employee(String name,int age){       this.name=name;       this.age=age;    } }

Output

Raja is eligible by age Adithya is eligible by age ---------------------------- Adithya is eligible by name
Updated on: 2020-07-11T12:38:14+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements