Java - Use predicate without lambda expressions

倾然丶 夕夏残阳落幕 提交于 2019-12-01 09:13:12

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

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.

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