JAVA 排序比较器

import java.util.Comparator;
import java.util.TreeSet;

public class orderDemo {
    public static void main(String[] args) {
        TreeSet<Student> s = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                //以年龄进行排序
                int num =o1.getAge()-o2.getAge();
                int num2 =num == 0 ? o1.getName().compareTo(o2.getName()):num;
                return  num2;
            }
        });
        //定义student
        Student s1 = new Student(10,"张三");
        Student s2 = new Student(11,"张二");
        Student s3 = new Student(11,"李四");
        Student s4 = new Student(10,"王五");
        Student s5 = new Student(10,"找流");
        s.add(s1);
        s.add(s2);
        s.add(s3);
        s.add(s4);
        s.add(s5);
        for (Student ss:s){
            System.out.print(ss.getName()+":"+ss.getAge()+"\r\n");
        }
    }
}

 

posted @ 2022-03-31 23:09  phpwyl  阅读(77)  评论(0编辑  收藏  举报