一、如何使用Collections工具类进行排序

使用Collections工具类进行排序主要有两种方式:

1.对象实现Comparable接口,重写compareTo方法

/**
 * @author Hanstrovsky
 */
@Data
@AllArgsConstructor
public class Student implements Comparable {
    String name;
    int age;

    @Override
    public int compareTo(Object o) {
        Student stu = (Student) o;
        //this-参数:升序;参数-this:降序
        return this.age - stu.age;
    }
}
/**
 * @author Hanstrovsky
 */
public class Test01 {
    public static void main(String[] args) {

        List<Student> stuList = new ArrayList<>();
        stuList.add(new Student("abc", 17));
        stuList.add(new Student("cab", 18));

        Collections.sort(stuList);
        System.out.println(stuList);
    }
}

2.传入一个比较器对象Comparator。

还是用上面的student,不去实现Comparable接口。

/**
 * @author Hanstrovsky
 */
public class Test02 {
    public static void main(String[] args) {
        List<Student> stuList = new ArrayList<>();
        stuList.add(new Student("abc", 19));
        stuList.add(new Student("cab", 18));

        Collections.sort(stuList, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.age - o2.age;
            }
        });
        System.out.println(stuList);
    }
}

二、依据多个字段排序

当需求要求先按第一个字段排序,如果第一个字段相同,则按第二个字段排序,如果第二个相同,则按第三个字段… 可以定义多个Comparator,并依次使用。

/**
 * @author Hanstrovsky
 */
@Data
@AllArgsConstructor
public class Student {
    // 编号
    private String id;
    // 身高
    private int height;
    // 体重
    private int weight;
}
/**
 * @author Hanstrovsky
 */
public class Test03 {
    public static void main(String[] args) {
        Student s1 = new Student("1", 180, 80);
        Student s2 = new Student("2", 175, 80);
        Student s3 = new Student("3", 175, 90);

        List<Student> students = new ArrayList<>();
        students.add(s1);
        students.add(s2);
        students.add(s3);
        System.out.println("原始排序:" + students);

        //按照身高升序排序
        Comparator<Student> byHeight = Comparator.comparing(Student::getHeight);
        //按照体重升序排序
        Comparator<Student> byWeight = Comparator.comparing(Student::getWeight);

        //将list先按照"身高"升序再按照"体重"升序排列
        students.sort(byHeight.thenComparing(byWeight));
        //将list先按照"身高"升序再按照"体重"升序排列
        System.out.println("优先身高:" + students);

        //将list先按照"体重"升序再按照"身高"升序排列
        students.sort(byWeight.thenComparing(byHeight));
        //将list先按照"身高"升序再按照"体重"升序排列
        System.out.println("优先体重:" + students);
    }
}

版权声明:本文为hanstrovsky原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/hanstrovsky/p/12520142.html