| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- package homework0804.util;
- import homework0804.entity.Person;
- import homework0804.entity.Student;
- import homework0804.manager.StudentManager;
- import java.util.*;
- /**
- * @author WanJl
- * @version 1.0
- * @title RankUtil
- * @description
- * @create 2026/8/6
- */
- public class RankUtil {
- /**
- * 功能 1:成绩排行榜 —— TreeSet 自然排序
- * 利用 Student 的 compareTo(平均分降序,相同按学号),
- * 把学生添加进 TreeSet<Student>,迭代器遍历输出排行榜
- */
- public static void showRank(StudentManager sm) {
- // TODO: 1) 从 sm.getStudents() 拿到 ArrayList<Student>
- // 2) 创建 TreeSet<Student>,把所有学生 add 进去(自动按自然排序排好 + 去重)
- // 3) 用 Iterator 遍历输出,格式:排名-学号-姓名-平均分
- List<Student> studentList = sm.getStudents();
- TreeSet<Student> treeSet=new TreeSet<>(studentList);
- Iterator<Student> iterator = treeSet.iterator();
- while (iterator.hasNext()){
- System.out.println(iterator.next());
- }
- }
- /**
- * 功能 2:按姓名排序 —— Comparator 匿名内部类
- * 使用 Collections.sort(list, new Comparator<Student>() {...}),
- * 匿名内部类中 o1.getName().compareTo(o2.getName())
- */
- public static void sortByName(StudentManager sm) {
- // TODO: 拷贝一份学生列表,Collections.sort + 匿名内部类 Comparator 按姓名升序
- List<Student> studentList = sm.getStudents();
- Collections.sort(studentList, new Comparator<Student>() {
- @Override
- public int compare(Student o1, Student o2) {
- return o1.getName().compareTo(o2.getName());
- }
- });
- // 遍历输出
- sm.printAll();
- }
- /**
- * 功能 3:按年龄排序 —— Comparator + Lambda
- * 使用 Collections.sort(list, (s1, s2) -> Integer.compare(s1.getAge(), s2.getAge()));
- */
- public static void sortByAge(StudentManager sm) {
- // TODO: 拷贝学生列表,用 Lambda 按年龄升序排序,遍历输出
- List<Student> studentList = sm.getStudents();
- Collections.sort(studentList, (s1, s2) -> Integer.compare(s1.getAge(), s2.getAge()));
- sm.printAll();
- }
- /**
- * 功能 4:按平均分降序(和自然排序对比)—— 用 Collections.sort + 匿名内部类
- * 要求:不依赖 Student 的 compareTo,在 Comparator 中自己算平均分(Double.compare 降序)
- */
- public static void sortByAvgDesc(StudentManager sm) {
- // TODO: Double.compare(o2.getAvgScore(), o1.getAvgScore()) 实现降序
- List<Student> studentList = sm.getStudents();
- Collections.sort(studentList, new Comparator<Student>() {
- @Override
- public int compare(Student o1, Student o2) {
- return Double.compare(o2.getAvgScore(), o1.getAvgScore());
- }
- });
- sm.printAll();
- }
- }
|