如何在 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

更新時間:2020 年 7 月 13 日

瀏覽量 728 次

開啟您的事業

完成課程,獲得認證

開始
廣告