假设有一个Student类,其中包含属性name和age,可以按照如下方式对List进行按年龄顺序排序:

  1. 实现Comparator接口
import java.util.Comparator;

public class StudentAgeComparator implements Comparator<Student> {
    @Override
    public int compare(Student s1, Student s2) {
        return s1.getAge() - s2.getAge();
    }
}
  1. 使用Collections.sort()方法进行排序
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Alice", 20));
        students.add(new Student("Bob", 18));
        students.add(new Student("Charlie", 22));
        students.add(new Student("David", 19));

        Collections.sort(students, new StudentAgeComparator());

        for (Student student : students) {
            System.out.println(student.getName() + " " + student.getAge());
        }
    }
}

输出结果为:

Bob 18
David 19
Alice 20
Charlie 22
``
java list集合按年龄顺序排序

原文地址: https://www.cveoy.top/t/topic/hgr7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录