Java List.Sort使用方法详解

发布时间:2023-05-24

一、语法与功能

List.Sort() 方法用来对 List 中的元素进行排序,可以用 lambda 表达式或者 Comparator 实现自定义排序。调用 syntax 如下:

List.sort(Comparator<? super E> c)

其中的 c 是按照指定的排序规则进行排序,可以为 lambda 表达式或者 Comparator 对象。

二、使用教程

1. 使用升序排序

对于基本类型,可以使用 Collections.sort 进行排序,对于自定义类型,需要实现 Comparable 接口并重写 compareTo 方法。

List<String> stringList = Arrays.asList("cat", "dog", "apple", "banana");
Collections.sort(stringList); // 升序排序
System.out.println(stringList); // [apple, banana, cat, dog]
List<Integer> integerList = Arrays.asList(2, 8, 1, 4);
Collections.sort(integerList);
System.out.println(integerList); // [1, 2, 4, 8]
class Student implements Comparable<Student> {
    private String name;
    private int score;
    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }
    @Override
    public int compareTo(Student o) {
        return score - o.score;
    }
}
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("Tom", 80));
studentList.add(new Student("Jerry", 60));
studentList.add(new Student("Bob", 70));
Collections.sort(studentList);
System.out.println(studentList); // [{name=Jerry, score=60}, {name=Bob, score=70}, {name=Tom, score=80}]

2. 使用降序排序

使用升序排列的代码仅需将 Collections.sort 更改为 Collections.reverse() 即可。

Collections.sort(stringList, Collections.reverseOrder());
System.out.println(stringList); // [dog, cat, banana, apple]
Collections.sort(integerList, Collections.reverseOrder());
System.out.println(integerList); // [8, 4, 2, 1]
Collections.sort(studentList, Collections.reverseOrder());
System.out.println(studentList); // [{name=Tom, score=80}, {name=Bob, score=70}, {name=Jerry, score=60}]

3. 使用自定义比较器

使用自定义比较器可以对任意类型进行排序。

List<String> stringList = Arrays.asList("cat", "dog", "apple", "banana");
stringList.sort((a, b) -> a.length() - b.length());
System.out.println(stringList); // [cat, dog, apple, banana]
List<Integer> integerList = Arrays.asList(2, 8, 1, 4);
integerList.sort((a, b) -> b - a);
System.out.println(integerList); // [8, 4, 2, 1]
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("Tom", 80));
studentList.add(new Student("Jerry", 60));
studentList.add(new Student("Bob", 70));
studentList.sort(Comparator.comparing(Student::getName));
System.out.println(studentList); // [{name=Bob, score=70}, {name=Jerry, score=60}, {name=Tom, score=80}]

三、总结

Java List.sort() 方法是一个非常有用的方法,可以对 List 中的元素按照指定规则进行排序。通过本文的介绍,相信大家已经掌握了其使用方法,并且可以根据需要实现自定义排序规则。