如何在 Java 8 中使用帶方法引用的 Comparator 對列表進行排序?
Java 8 在 Comparator 介面中引入了更改,該介面允許我們比較兩個物件。這些更改有助於我們更輕鬆地建立比較器。新增的第一個重要方法是 comparing() 方法。此方法接收一個作為引數的 Function ,用於確定要比較的值,並建立 Comparator。另一個重要方法是 thenComparing() 方法。此方法可用於組合 Comparator。
在下面的示例中,我們可以使用 comparing() 方法按姓氏對列表進行排序,然後使用 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 class
class 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]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP