如何在 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP