Java - Use predicate without lambda expressions

二次信任 提交于 2020-01-21 08:28:21

问题


I've 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 test whether the age which i pass to Predicate is adult or not using the method defined in Employee class , for which i am passing the method reference which i pass in the constructor of Predicate class.

But i don't know how to call the method defined in Employee class, 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 the compilation error in the System.out.println("Test result is "+ isAdult(age)); in the predicate class.

Let me know how to resolve this issue. and if i need to provide any other information.


回答1:


Predicate interface has method test(). You should use this method in a following way:

isAdult.test(age)

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




回答2:


This looks a little bit suspicious, you care if the employee is an adult, so your method should really take a Employee as an argument and a Predicate<Employee>, like this:

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

And the usage of this method would be:

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

The thing is you can reuse this method for other predicates as well, let's say you want to test gender, or income, etc.




回答3:


Predicate has test method, that is used, when working with streams/optionals.

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


来源:https://stackoverflow.com/questions/44583847/java-use-predicate-without-lambda-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!