從 Java 8 開始,你可以使用 Stream
API 對 List
進行排序,這種方式更加簡潔和靈活。
以下是一個示例代碼:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;// 自定義對象類
class Employee {private String name;private double salary;public Employee(String name, double salary) {this.name = name;this.salary = salary;}public String getName() {return name;}public double getSalary() {return salary;}@Overridepublic String toString() {return "Employee{name='" + name + "', salary=" + salary + "}";}
}public class Main {public static void main(String[] args) {// 創建一個包含自定義對象的 ListList<Employee> employees = new ArrayList<>();employees.add(new Employee("Alice", 5000.0));employees.add(new Employee("Bob", 4000.0));employees.add(new Employee("Charlie", 6000.0));// 使用 Stream API 按工資升序排序List<Employee> sortedEmployees = employees.stream().sorted(Comparator.comparingDouble(Employee::getSalary)).collect(Collectors.toList());// 輸出排序后的結果for (Employee employee : sortedEmployees) {System.out.println(employee);}}
}
在上述代碼中,我們使用 Stream
API 的 sorted
方法和 Comparator.comparingDouble
方法按工資升序對 List
進行排序,最后使用 collect
方法將排序后的元素收集到一個新的 List
中。