在 Java 中,可以对包含自定义元素的List集合进行排序。通常可以使用Collections.sort()方法结合自定义的比较器来实现。
一、定义包含自定义元素的类
假设我们有一个表示学生的类Student:
class Student {private int id;private String name;private int age;public Student(int id, String name, int age) {this.id = id;this.name = name;this.age = age;}public int getId() {return id;}public String getName() {return name;}public int getAge() {return age;}@Overridepublic String toString() {return "Student{" +"id=" + id +", name='" + name + '\'' +", age=" + age +'}';}
}
二、使用Collections.sort()进行排序
按学生年龄升序排序:
import java.util.ArrayList;
import java.util.List;public class ListSortCustomElementsExample {public static void main(String[] args) {List<Student> students = new ArrayList<>();students.add(new Student(1, "Alice", 20));students.add(new Student(2, "Bob", 18));students.add(new Student(3, "Charlie", 22));students.add(new Student(4, "Charlie", 30));students.add(new Student(5, "Charlie", 12));students.sort((s1, s2) -> s1.getAge() - s2.getAge());for (Student student : students) {System.out.println(student);}}
}