JavaSE-16.2.2【案例-ArrayList集合存储学生并排序】

 1 package day7.lesson2;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.Comparator;
 6 
 7 /*
 8 2.2 案例-ArrayList集合存储学生并排序
 9     ArrayList存储学生对象,使用Collections对ArrayList进行排序
10     要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
11  */
12 public class CollectionsDemo2 {
13     public static void main(String[] args) {
14         ArrayList<Student> arrayList = new ArrayList<>();
15 
16         Student s1 = new Student("xiyangyang", 11);
17         Student s2 = new Student("lanyangyang", 13);
18         Student s3 = new Student("feiyangyang", 15);
19         Student s4 = new Student("meiyangyang", 11);
20 
21         arrayList.add(s1);
22         arrayList.add(s2);
23         arrayList.add(s3);
24         arrayList.add(s4);
25 
26         //使用Collections对ArrayList集合排序
27         //sort•(List<T> list, Comparator<? super T> c)
28         Collections.sort(arrayList, new Comparator<Student>() { //匿名内部类比较器
29             @Override
30             public int compare(Student s1, Student s2) {
31                 int num = s1.getAge() - s2.getAge();
32                 int num2 = (num==0 ? s1.getName().compareTo(s2.getName()) : num);
33                 return num2;
34             }
35         });
36 
37         for (Student s: arrayList){
38             System.out.println(s.getName() + "," + s.getAge());
39         }
40     }
41 }
 1 package day7.lesson2;
 2 
 3 public class Student {
 4 
 5     private String name;
 6     private int age;
 7 
 8     public Student() {
 9     }
10 
11     public Student(String name, int age) {
12         this.name = name;
13         this.age = age;
14     }
15 
16     public void setName(String name) {
17         this.name = name;
18     }
19 
20     public void setAge(int age) {
21         this.age = age;
22     }
23 
24     public String getName() {
25         return name;
26     }
27 
28     public int getAge() {
29         return age;
30     }
31 }

 

posted @ 2021-06-02 19:40  yub4by  阅读(78)  评论(0编辑  收藏  举报