Collections.sort()用于对List集合排序,支持自然排序和自定义Comparator排序,基于稳定算法实现。
在Java中,Collections.sort() 是对集合进行排序的常用方法,适用于实现了 List 接口的集合类型。它基于稳定的排序算法(归并排序或优化的快速排序),能够高效地对元素进行自然排序或自定义排序。
当集合中的元素类型实现了 Comparable 接口时,可以直接调用 Collections.sort() 进行自然排序。
示例代码:
Listnames = new ArrayList<>(); names.add("Alice"); names.add("Charlie"); names.add("Bob"); Collections.sort(names); System.out.println(names); // 输出: [Alice, Bob, Charlie]
若需要自定义排序规则,可传入一个 Comparator 实现作为第二个参数。
示例:按字符串长度排序
Listwords = Arrays.asList("apple", "hi", "banana", "ok"); Collections.sort(words, (a, b) -> a.length() - b.length()); System.out.println(words); // 输出: [hi, ok, apple, banana]
假设有一个 Person 类,包含 name 和 age 字段,可以通过 Comparator 按年龄排序。
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
List people = new ArrayList<>();
people.add(new Person("Tom", 30));
people.add(new Person("Jane", 25));
people.add(new Person("Lee", 35));
Collections.sort(people, (p1, p2) -> p1.age - p2.age);
// 遍历输出
for (Person p : people) {
System.out.println(p.name + ": " + p.age);
}
// 输出: Jane(25), Tom(30), Lee(35)
使用 Collections.sort() 时需注意以下几点:
例如使用 Stream 排序:
Listsorted = words.stream() .sorted((a, b) -> a.length() - b.length()) .collect(Collectors.toList());
基本上就这些。Collections.sort 虽然传统但依然实用,掌握它有助于理解 Java 集合排序机制。实际开发中可根据需求选择更现代的写法。不复杂但容易忽略细节。