如何使用Comparator和Java 8中的方法引用对列表进行排序?
Java8在Comparator 接口中引入了更改,使我们可以比较两个对象。这些更改有助于我们更轻松地创建比较器。添加的第一个重要方法是compare()方法。此方法接收确定要比较的值并创建Comparator的参数Function 。另一个重要的方法是thenComparing()方法。此方法可用于组成Comparator。
在下面的例子中,我们可以用一个列表排序, 第一个名字与比较() 方法,然后将姓氏与thenComparing()的方法比较接口。
示例
import java.util.*; public class MethodReferenceSortTest { public static void main(String[] args) { List<Employee> emp = new ArrayList<Employee>(); emp.add(new Employee(25, "Raja", "Ramesh")); emp.add(new Employee(30, "Sai", "Adithya")); emp.add(new Employee(28, "Jai", "Dev")); emp.add(new Employee(23, "Ravi", "Chandra")); emp.add(new Employee(35, "Chaitanya", "Krishna")); // using method reference emp.stream().sorted(Comparator.comparing(Employee::getFirstName) .thenComparing(Employee::getLastName)) .forEach(System.out::println); } }// Employee classclass Employee { int age; String firstName; String lastName; public Employee(int age, String firstName, String lastName) { super(); this.age = age; this.firstName = firstName; this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return "Employee [age=" + age + ", firstName=" + firstName + ", lastName=" + lastName + "]"; } }
输出结果
Employee [age=35, firstName=Chaitanya, lastName=Krishna] Employee [age=28, firstName=Jai, lastName=Dev] Employee [age=25, firstName=Raja, lastName=Ramesh] Employee [age=23, firstName=Ravi, lastName=Chandra] Employee [age=30, firstName=Sai, lastName=Adithya]