RankUtil.java 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package homework0804.util;
  2. import homework0804.entity.Person;
  3. import homework0804.entity.Student;
  4. import homework0804.manager.StudentManager;
  5. import java.util.*;
  6. /**
  7. * @author WanJl
  8. * @version 1.0
  9. * @title RankUtil
  10. * @description
  11. * @create 2026/8/6
  12. */
  13. public class RankUtil {
  14. /**
  15. * 功能 1:成绩排行榜 —— TreeSet 自然排序
  16. * 利用 Student 的 compareTo(平均分降序,相同按学号),
  17. * 把学生添加进 TreeSet<Student>,迭代器遍历输出排行榜
  18. */
  19. public static void showRank(StudentManager sm) {
  20. // TODO: 1) 从 sm.getStudents() 拿到 ArrayList<Student>
  21. // 2) 创建 TreeSet<Student>,把所有学生 add 进去(自动按自然排序排好 + 去重)
  22. // 3) 用 Iterator 遍历输出,格式:排名-学号-姓名-平均分
  23. List<Student> studentList = sm.getStudents();
  24. TreeSet<Student> treeSet=new TreeSet<>(studentList);
  25. Iterator<Student> iterator = treeSet.iterator();
  26. while (iterator.hasNext()){
  27. System.out.println(iterator.next());
  28. }
  29. }
  30. /**
  31. * 功能 2:按姓名排序 —— Comparator 匿名内部类
  32. * 使用 Collections.sort(list, new Comparator<Student>() {...}),
  33. * 匿名内部类中 o1.getName().compareTo(o2.getName())
  34. */
  35. public static void sortByName(StudentManager sm) {
  36. // TODO: 拷贝一份学生列表,Collections.sort + 匿名内部类 Comparator 按姓名升序
  37. List<Student> studentList = sm.getStudents();
  38. Collections.sort(studentList, new Comparator<Student>() {
  39. @Override
  40. public int compare(Student o1, Student o2) {
  41. return o1.getName().compareTo(o2.getName());
  42. }
  43. });
  44. // 遍历输出
  45. sm.printAll();
  46. }
  47. /**
  48. * 功能 3:按年龄排序 —— Comparator + Lambda
  49. * 使用 Collections.sort(list, (s1, s2) -> Integer.compare(s1.getAge(), s2.getAge()));
  50. */
  51. public static void sortByAge(StudentManager sm) {
  52. // TODO: 拷贝学生列表,用 Lambda 按年龄升序排序,遍历输出
  53. List<Student> studentList = sm.getStudents();
  54. Collections.sort(studentList, (s1, s2) -> Integer.compare(s1.getAge(), s2.getAge()));
  55. sm.printAll();
  56. }
  57. /**
  58. * 功能 4:按平均分降序(和自然排序对比)—— 用 Collections.sort + 匿名内部类
  59. * 要求:不依赖 Student 的 compareTo,在 Comparator 中自己算平均分(Double.compare 降序)
  60. */
  61. public static void sortByAvgDesc(StudentManager sm) {
  62. // TODO: Double.compare(o2.getAvgScore(), o1.getAvgScore()) 实现降序
  63. List<Student> studentList = sm.getStudents();
  64. Collections.sort(studentList, new Comparator<Student>() {
  65. @Override
  66. public int compare(Student o1, Student o2) {
  67. return Double.compare(o2.getAvgScore(), o1.getAvgScore());
  68. }
  69. });
  70. sm.printAll();
  71. }
  72. }