i_am_zero..
26
它似乎有点晚了,但这是我的两分钱.甲lambda表达式用于创建匿名方法.除了调用现有方法之外什么都不做,但直接通过名称引用该方法更为明确.和方法的参考,使我们在使用方法参照运营商来做::.
考虑以下简单类,其中每个员工都有一个名称和等级.
public class Employee {
private String name;
private String grade;
public Employee(String name, String grade) {
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
假设我们有一个通过某种方法返回的员工列表,我们希望按其等级对员工进行排序.我们知道我们可以使用匿名类:
List employeeList = getDummyEmployees();
// Using anonymous class
employeeList.sort(new Comparator() {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getGrade().compareTo(e2.getGrade());
}
});
其中getDummyEmployee()是一些方法:
private static List getDummyEmployees() {
return Arrays.asList(new Employee("Carrie", "C"),
new Employee("Fanishwar", "F"),
new Employee("Brian", "B"),
new Employee("Donald", "D"),
new Employee("Adam", "A"),
new Employee("Evan", "E")
);
}
现在我们知道Comparator是一个功能接口.甲功能接口是具有正好一个抽象方法(尽管它可含有一个或多个默认的或静态的方法).Lambda表达式提供了实现,@FunctionalInterface因此功能接口只能有一个抽象方法.我们可以使用lambda表达式:
employeeList.sort((e1,e2) -> e1.getGrade().compareTo(e2.getGrade())); // lambda exp
看起来一切都很好但是如果课程Employee也提供了类似的方法:
public class Employee {
private String name;
private String grade;
// getter and setter
public static int compareByGrade(Employee e1, Employee e2) {
return e1.grade.compareTo(e2.grade);
}
}
在这种情况下,使用方法名称本身将更加清晰.因此我们可以通过使用方法引用直接引用方法:
employeeList.sort(Employee::compareByGrade); // method reference
根据文档,有四种方法参考:
+----+-------------------------------------------------------+--------------------------------------+
| | Kind | Example |
+----+-------------------------------------------------------+--------------------------------------+
| 1 | Reference to a static method | ContainingClass::staticMethodName |
+----+-------------------------------------------------------+--------------------------------------+
| 2 |Reference to an instance method of a particular object | containingObject::instanceMethodName |
+----+-------------------------------------------------------+--------------------------------------+
| 3 | Reference to an instance method of an arbitrary object| ContainingType::methodName |
| | of a particular type | |
+----+-------------------------------------------------------+--------------------------------------+
| 4 |Reference to a constructor | ClassName::new |
+------------------------------------------------------------+--------------------------------------+