方法引用是lambda表达式的简化形式。方法名后面可以指定一个实例或一个方法名。“::”符号可以将方法名与对象或类的名称分开。
实例方法引用引用任何类的实例方法。 在下面的示例中,我们可以使用类名实现实例方法引用。
<Class-Name>::<Instance-Method-Name>
import java.util.*;; import java.util.function.*; public class ClassNameRefInstanceMethodTest { public static void main(String args[]) { List<Employee> empList = Arrays.asList( new Employee("Raja", 15000), new Employee("Adithya", 12000), new Employee("Jai", 9000), new Employee("Ravi", 19000), new Employee("Surya", 8500), new Employee("Chaitanya", 7500), new Employee("Vamsi", 14000) ); Function<Employee, String> getEmployeeNameFunction = new Function<Employee, String>() { @Override public String apply(Employee e) { return e.getName(); } }; System.out.println("薪水大于10000的员工列表:"); empList.stream() .filter(e -> e.getSalary() > 10000) .map(Employee::getName) //实例方法使用类名“Employee”引用“getName” .forEach(e -> System.out.println(e)); } } // Employee 类 class Employee { private String name; private int salary; public Employee(String name, int salary){ this.name = name; this.salary = salary; } public String getName() { return name; } public int getSalary() { return salary; } }
输出结果
薪水大于10000的员工列表: Raja Adithya Ravi Vamsi