从 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
中。