Java - use predicate without lambda expressions

I have below requirement: -

Employee.java

public boolean isAdult(Integer age) {
    if(age >= 18) {
        return true;
    }
    return false;
}

      

Predicate.java

    private Integer age;
Predicate<Integer> isAdult;

public PredicateAnotherClass(Integer age, Predicate<Integer> isAdult) {
    this.age = age;
    System.out.println("Test result is "+ isAdult(age));
}

public void testPredicate() {
    System.out.println("Calling the method defined in the manager class");

}

      

Now my goal is to check if the age I am passing in Predicate

is adult or not using the method defined in the class Employee

for which I am passing the method reference that I am passing in the class constructor Predicate

.

But I don't know how to call the method defined in the class Employee

, below is my test class: -

public class PredicateTest {

    public static void main(String[] args) {
        PredicateManager predicateManager = new PredicateManager();

        PredicateAnotherClass predicateAnotherClass = new PredicateAnotherClass(20, predicateManager::isAdult);
        predicateAnotherClass.testPredicate();;
    }
}

      

I am getting compile error in System.out.println("Test result is "+ isAdult(age));

in class Predicate

.

Please let me know how to fix this problem. and if I need to provide any other information.

+3


source to share


3 answers


The predicate interface has a method test()

. You should use this method like this:

isAdult.test(age)

      



This method evaluates this predicate for the given argument. It returns true if the input argument matches the predicate, false otherwise

+1


source


This looks a little suspicious, you don't care if the employee is an adult, so your method should really take Employee

as an argument and Predicate<Employee>

, for example:

 private static void testEmployee(Employee emp, Predicate<Employee> predicate) {
    boolean result = predicate.test(emp);
    System.out.println(result);
}

      

And using this method would be:



testEmployee(new Employee(13), emp -> emp.isAdult(emp.getAge()));

      

The point is that you can reuse this method for other predicates, say you want to check gender, or income, etc.

+4


source


The predicate has a testing method that is used when working with streams / options.

public PredicateAnotherClass(Integer age, Predicate<Integer> isAdultFilter) {
    this.age = age;
    System.out.println("Test result is "+ isAdultFilter.test(age));
}

      

+1


source







All Articles