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