关于List集合中元素排序问题

问题描述:

有一个list集合,其中元素是Student对象,根据student的age排序。

Student对象

/**
 * description
 *
 * @author 70KG
 * @date 2018/9/29
 */
@Data
public class Student implements Comparable<Student> {

    private String name;

    private Integer age;

    private Integer num;

    public Student() {
    }

    public Student(String name, Integer age, Integer num) {
        this.name = name;
        this.age = age;
        this.num = num;
    }

    @Override
    public int compareTo(Student student) {
        return student.getAge().compareTo(this.getAge());
    }
}

此类需要实现Comparable接口,重写compareTo方法

测试类:

/**
 * description
 *
 * @author 70KG
 * @date 2018/9/29
 */
public class TestController {

    public static void main(String[] args) {

        List<Student> list = new ArrayList<>();

        Student student1 = new Student("张三",21,1);
        Student student2 = new Student("李四",22,2);
        Student student3 = new Student("王五",23,3);
        Student student4 = new Student("赵六",24,4);

        list.add(student4);
        list.add(student1);
        list.add(student2);
        list.add(student3);

        System.out.println(list);

        Collections.sort(list);

        System.out.println(list);
    }

}

利用Collections.sort()方法进行重排序。

输出结果:

[Student(name=赵六, age=24, num=4), Student(name=张三, age=21, num=1), Student(name=李四, age=22, num=2), Student(name=王五, age=23, num=3)]
[Student(name=赵六, age=24, num=4), Student(name=王五, age=23, num=3), Student(name=李四, age=22, num=2), Student(name=张三, age=21, num=1)]

正序倒序,只需改变实体中的compareTo方法即可。

原文地址:https://www.cnblogs.com/zhangjianbing/p/9722210.html