Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Use predicate without lambda expressions

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.

like image 441
Rohit Avatar asked Apr 06 '26 16:04

Rohit


2 Answers

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.

like image 58
Eugene Avatar answered Apr 08 '26 04:04

Eugene


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

like image 29
Mykola Yashchenko Avatar answered Apr 08 '26 06:04

Mykola Yashchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!