对List<pojo>中的属性对集合进行排序

188 阅读1分钟

使用Collections.sort

实体类

@Data
public class Student {
    private String name;
    private Integer age;

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

方法一 直接调用

    ArrayList<Student> students = new ArrayList<>();
    students.add(new Student("张三",20));
    students.add(new Student("李四",16));
    students.add(new Student("王五",18));
    /**
     * Collections.sort(students,new Comparator<Student>() {
     *  相同写法
     * });
     */
    students.sort(new Comparator<Student>() {
        @Override
        public int compare(Student o1, Student o2) {
            if (o1.getAge()> o2.getAge()) {
                return 1;
            }else if (o1.getAge() < o2.getAge()) {
                return -1;
            }else {
                return 0;
            }
            //升序排列,降序排列互换return 1 和return -1的位置
        }
    });
    students.forEach(System.out::println);
}

方法二 在实体类重写compare方法,直接调用sort方法即可

```
@Data
public class Student implements Comparable<Student>{
    private String name;
    private Integer age;

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public int compareTo(Student o)
    {
        if (this.getAge() > o.getAge()){
            return 1;
        } else if (this.getAge() < o.getAge()) {
            return -1;
        }else {
            return 0;
        }
    }
}
```