使用方法参考 Java 8

Using method references of Java 8

我正在使用 Java 8 中支持的谓词,其中我正在使用 lambda,但我想使用方法引用来代替 lambda。请告知如何实现这一目标。下面是我的代码。

public class Employee {

   public Employee(Integer id, Integer age, String gender, String fName, String lName){
       this.id = id;
       this.age = age;
       this.gender = gender;
       this.firstName = fName;
       this.lastName = lName;
   }

   private Integer id;
   private Integer age;
   private String gender;
   private String firstName;
   private String lastName;

   //Please generate Getter and Setters

    @Override
    public String toString() {
        return this.id.toString()+" - "+this.age.toString(); //To change body of generated methods, choose Tools | Templates.
    }

这里我使用带有 lambda 的谓词,我想删除 lambda 并改用方法引用:

public class EmployeePredicates
{
    public static Predicate<Employee> isAdultMale() {
        return p -> p.getAge() > 21 && p.getGender().equalsIgnoreCase("M");
    }

    public static Predicate<Employee> isAdultFemale() {
        return p -> p.getAge() > 18 && p.getGender().equalsIgnoreCase("F");
    }

    public static Predicate<Employee> isAgeMoreThan(Integer age) {
        return p -> p.getAge() > age;
    }

    public static List<Employee> filterEmployees (List<Employee> employees, Predicate<Employee> predicate) {
        return employees.stream().filter( predicate ).collect(Collectors.<Employee>toList());
    }
}  

我需要用 "method reference syntax" 重写您的代码片段,以向您展示它们在此处的用法的所有怪异之处和不正确之处。请不要这样做!

public static Predicate<Employee> isAdultMale() {
    return e -> ((Predicate<Employee>)EmployeePredicates::isAgeMoreThan21).test(e) && ((Predicate<Employee>)EmployeePredicates::isMale).test(e);
}

private static boolean isAgeMoreThan21(Employee employee) {
    return employee.getAge() > 21;
}

private static boolean isMale(Employee employee) {
    return employee.getGender().equalsIgnoreCase("M");
}

方法引用通常不能用于逻辑表达式(如 methodReference1 && methodReference2)和需要一些额外信息的表达式(如方法 isAgeMoreThan(age) - 这就是为什么我必须将其转换为方法 isAgeMoreThan21()).

正如@tobias_k 所建议的,标准逻辑运算符可以替换为 Predicate 的相应方法以组合此类型的实例:

public static Predicate<Employee> isAdultMale() {
    return ((Predicate <Employee>)EmployeePredicates::isAgeMoreThan21).and(EmployeePredicates::isMale);
}