我正在使用Java 8中支持的谓词,我使用lambdas,但我想使用方法引用代替lambdas。请告知如何实现这一目标。以下是我的代码。
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.
}
在这里我使用lambdas的谓词,我想删除lambdas并使用方法引用:
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());
}
}
答案 0 :(得分:2)
我需要使用&#34;方法参考语法&#34;重写您的代码段。在这里向你展示他们使用的所有奇怪和不正确。请不要这样做!
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);
}