java,List集合单字段、多字段排序

如题,闲话少说直接上代码!

public class Solution0604 {

    public static void main(String[] args) {
        List<Student> studentList = new LinkedList<>();
        Student student1 = new Student();
        Student student2 = new Student();
        student1.setCode("2021060401");
        student1.setName("小明");
        student1.setAge(20);

        student2.setCode("2021060402");
        student2.setName("小红");
        student2.setAge(19);
        studentList.add(student1);
        studentList.add(student2);

        System.out.println("原集合");
        studentList.forEach(e -> {
            System.out.println(e.toString());
        });
        //对单字段排序,对age排序
        List<Student> list = studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
        System.out.println("对单字段排序");
        list.forEach(e -> {
            System.out.println(e.toString());
        });

        // 对双字段排序,code和age
        Comparator<Student> byCode = Comparator.comparing(Student::getCode);
        Comparator<Student> byAge = Comparator.comparing(Student::getAge);

        studentList.sort(byAge.thenComparing(byCode));
        System.out.println("先按年龄排序后集合");
        studentList.forEach(e -> {
            System.out.println(e.toString());
        });
        System.out.println("对上结果先按学号排序后集合");
        studentList.sort(byCode.thenComparing(byAge));
        studentList.forEach(e -> {
            System.out.println(e.toString());
        });
    }

}

class Student {

    private String code;

    private String name;

    private Integer age;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "code='" + code + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

打印结果:

原集合
Student{code='2021060401', name='小明', age=20}
Student{code='2021060402', name='小红', age=19}
对单字段排序
Student{code='2021060402', name='小红', age=19}
Student{code='2021060401', name='小明', age=20}
先按年龄排序后集合
Student{code='2021060402', name='小红', age=19}
Student{code='2021060401', name='小明', age=20}
对上结果先按学号排序后集合
Student{code='2021060401', name='小明', age=20}
Student{code='2021060402', name='小红', age=19}

版权声明:本文为leaf_c原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。