Collections.sort()用于列表排序,支持自然排序与自定义Comparator;可对String、Integer等实现Comparable的类型直接排序,也可通过实现Comparable接口或传入Comparator对自定义对象(如Person)按属性排序,Java 8后可用lambda表达式简化写法,底层采用稳定Timsort算法,要求列表可修改且非null,适用于RandomAccess或LinkedList结构。

在Java中,Collections.sort() 是一个非常常用的方法,用于对列表(List)中的元素进行排序。它位于 java.util.Collections 类中,支持对实现了 Comparable 接口的对象进行自然排序,也支持通过自定义的 Comparator 实现灵活排序。
Java 中像 String、Integer 等类已经实现了 Comparable 接口,因此可以直接使用 Collections.sort() 进行自然排序。
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Charlie");
names.add("Bob");
Collections.sort(names); // 按字母顺序排序
System.out.println(names); // 输出: [Alice, Bob, Charlie]
如果你有一个自定义类(如 Person),可以通过让该类实现 Comparable 接口来定义默认排序规则。
class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person other) {
return Integer.compare(this.age, other.age); // 按年龄升序
}
@Override
public String toString() {
return name + "(" + age + ")";
}
}
使用示例:
立即学习“Java免费学习笔记(深入)”;
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 20));
people.add(new Person("Charlie", 25));
Collections.sort(people);
System.out.println(people); // 按年龄排序输出
如果不希望修改类本身,或需要多种排序方式,可以传入 Comparator 作为参数。
// 按姓名排序
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
});
// Java 8 以后更简洁的写法:
people.sort(Comparator.comparing(Person::getName));
还可以实现逆序:
Collections.sort(people, Comparator.comparing(Person::getAge).reversed());
使用 Collections.sort() 时需注意以下几点:
以上就是如何在Java中使用Collections.sort排序的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号