如何在 Java 中將比較器寫成 lambda 表示式?


Lambda 表示式匿名方法,在 Java 中不單獨執行。相反,它用於實現由函式式介面定義的方法。任何函式式介面和Comparator都可以使用 Lambda 表示式,Comparator是函式式介面。使用Comparator介面時,在比較物件集合時會進行比較。

在以下示例中,我們可以使用Comparator介面透過名稱對員工列表進行排序。

示例

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Employee {
   int id;
   String name;
   double salary;
   public Employee(int id, String name, double salary) {
      super();
      this.id = id;
      this.name = name;
      this.salary = salary;
   }
}
public class LambdaComparatorTest {
   public static void main(String[] args) {
      List<Employee> list = new ArrayList<Employee>();

      // Adding employees
      list.add(new Employee(115, "Adithya", 25000.00));
      list.add(new Employee(125, "Jai", 30000.00));
      list.add(new Employee(135, "Chaitanya", 40000.00));
      System.out.println("Sorting the employee list based on the name");

      // implementing lambda expression
      Collections.sort(list, (p1, p2) -> {
         return p1.name.compareTo(p2.name); 
      }); 
      for(Employee e : list) {
         System.out.println(e.id + " " + e.name + " " + e.salary);
      }
   }
}

輸出

Sorting the employee list based on the name
115 Adithya 25000.0
135 Chaitanya 40000.0
125 Jai 30000.0

更新於: 2019-12-06

4K+ 瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.