Java 比较器排序Comparator的使用

阅读 43

2022-01-26

存储学生对象并遍历,创建TreeSet集合使用带参构造方法
要求:按照年龄从小到大排序,年龄相同时,按照字母的顺序排序

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

public class TressSetDemo3 {
    public static void main(String[] args) {
        //创建集合对象
        TreeSet<Student> ts=new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                int num = s1.getAge() - s2.getAge();
                int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                return num2;
            }
        });

        //创建学生对象
        Student s1 = new Student("张三", 18);
        Student s2 = new Student("李四", 19);
        Student s3 = new Student("王五", 17);
        Student s4 = new Student("陈六", 18);
        Student s5 = new Student("吴一", 18);

        //把学生添加到集合
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);

        //遍历集合
        for (Student s : ts) {
            System.out.println(s.getName()+","+s.getAge());
        }
    }
}

精彩评论(0)

0 0 举报