java如何对list排序
使用Collections.sort()方法
对List进行排序的最简单方法是使用Collections.sort()。该方法会对列表进行自然排序(升序)。
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
List<Integer> numbers = new ArrayList<>(List.of(3, 1, 4, 1, 5, 9));
Collections.sort(numbers); // 升序排序
System.out.println(numbers); // [1, 1, 3, 4, 5, 9]
使用Comparator自定义排序
如果需要降序或自定义排序规则,可以传入Comparator。
Collections.sort(numbers, Collections.reverseOrder()); // 降序排序
System.out.println(numbers); // [9, 5, 4, 3, 1, 1]
或者使用Lambda表达式自定义比较逻辑:
List<String> words = new ArrayList<>(List.of("apple", "banana", "cherry"));
Collections.sort(words, (a, b) -> b.compareTo(a)); // 按字母降序
System.out.println(words); // ["cherry", "banana", "apple"]
使用List.sort()方法(Java 8+)
Java 8及以上版本可以直接调用List.sort()方法,语法更简洁。
numbers.sort(Comparator.naturalOrder()); // 升序
words.sort(Comparator.reverseOrder()); // 降序
对对象列表排序
如果List存储的是自定义对象,可以通过实现Comparable接口或传入Comparator。
class Person {
String name;
int age;
// 构造方法、getter/setter省略
}
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
// 按年龄升序排序
people.sort(Comparator.comparingInt(Person::getAge));
// 按姓名降序排序
people.sort(Comparator.comparing(Person::getName).reversed());
使用Stream API排序(Java 8+)
通过Stream可以生成新的排序列表而不修改原列表。
List<Integer> sortedNumbers = numbers.stream()
.sorted()
.toList(); // 升序排序的新列表
List<String> reverseSortedWords = words.stream()
.sorted(Comparator.reverseOrder())
.toList(); // 降序排序的新列表
注意事项
- 对于基本类型列表(如
List<Integer>),直接使用Collections.sort()或List.sort()即可。 - 自定义对象排序需明确比较规则(
Comparable或Comparator)。 - 使用
Stream.sorted()会生成新列表,原列表不受影响。







