Java 使用 Collections.sort() 和 Comparator 对学生列表按年龄排序
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);
}
}
}
代码说明
-
创建 Student 类: 定义一个 Student 类,包含
name和age属性,并提供构造方法。 -
创建学生列表: 创建一个
ArrayList对象,并添加三个学生实例。 -
使用 Collections.sort() 和 Comparator: 使用
Collections.sort()方法对列表进行排序,并传入一个Comparator对象。Comparator接口定义了compare()方法,用于比较两个学生对象的年龄,返回一个整数值表示比较结果。 -
打印排序结果: 使用
for循环遍历排序后的列表,并打印每个学生的姓名和年龄。
输出结果
a 20
b 21
c 22
总结
通过使用 Collections.sort() 方法和 Comparator 接口,我们可以轻松地对学生列表按照年龄进行排序。Comparator 接口提供了一个灵活的机制,允许我们根据不同的标准对列表进行排序。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/mTxF 著作权归作者所有。请勿转载和采集!