如何在 Java 中使用类名称实现实例方法引用?
方法引用是λ 表达式的简化形式。它可以指定一个类名或实例名,后跟方法名。“::”符号可以将方法名与对象或类的名称分隔开来。
实例方法引用是指任何类的实例方法。在下面的示例中,我们可以使用类名实现实例方法引用。
语法
<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("The list of employees whose salary greater than 10000:"); empList.stream() .filter(e -> e.getSalary() > 10000) .map(Employee::getName) // instance method reference "getName" using class name "Employee" .forEach(e -> System.out.println(e)); } } // Employee class 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; } }
输出
The list of employees whose salary greater than 10000: Raja Adithya Ravi Vamsi
广告