Java 使用 Collections.sort() 和 Comparator 对学生列表按年龄排序

本文将演示如何使用 Java 的 Collections.sort() 方法和 Comparator 接口,根据年龄对一个包含学生对象的列表进行排序。

代码示例

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Student {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Student> list1 = new ArrayList<>();
        list1.add(new Student('a', 20));
        list1.add(new Student('b', 21));
        list1.add(new Student('c', 22));

        Collections.sort(list1, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                return s1.age - s2.age;
            }
        });

        for (Student s : list1) {
            System.out.println(s.name + ' ' + s.age);
        }
    }
}

代码说明

  1. 创建 Student 类: 定义一个 Student 类,包含 name 和 age 属性,并提供构造方法。

  2. 创建学生列表: 创建一个 ArrayList 对象,并添加三个学生实例。

  3. 使用 Collections.sort() 和 Comparator: 使用 Collections.sort() 方法对列表进行排序,并传入一个 Comparator 对象。Comparator 接口定义了 compare() 方法,用于比较两个学生对象的年龄,返回一个整数值表示比较结果。

  4. 打印排序结果: 使用 for 循环遍历排序后的列表,并打印每个学生的姓名和年龄。

输出结果

a 20
b 21
c 22

总结

通过使用 Collections.sort() 方法和 Comparator 接口,我们可以轻松地对学生列表按照年龄进行排序。Comparator 接口提供了一个灵活的机制,允许我们根据不同的标准对列表进行排序。

Java 使用 Collections.sort() 和 Comparator 对学生列表按年龄排序