java集合如何排序
Java集合排序方法
Java提供了多种方式对集合进行排序,主要依赖于Collections工具类和List接口的默认方法。以下是常用的排序方法:

使用Collections.sort()对List排序
List<Integer> numbers = Arrays.asList(5, 3, 8, 1);
Collections.sort(numbers); // 默认升序
System.out.println(numbers); // 输出 [1, 3, 5, 8]
使用自定义Comparator排序
List<String> names = Arrays.asList("John", "Alice", "Bob");
Collections.sort(names, (a, b) -> b.compareTo(a)); // 降序
System.out.println(names); // 输出 [John, Bob, Alice]
使用List.sort()方法(Java 8+)
List<Integer> numbers = Arrays.asList(5, 3, 8, 1);
numbers.sort(Comparator.naturalOrder()); // 升序
System.out.println(numbers); // 输出 [1, 3, 5, 8]
对自定义对象排序
需要实现Comparable接口或提供Comparator:
class Person implements Comparable<Person> {
String name;
int age;
@Override
public int compareTo(Person other) {
return this.age - other.age;
}
}
List<Person> people = ...;
Collections.sort(people); // 按年龄升序
使用Stream API排序(Java 8+)
List<String> names = Arrays.asList("John", "Alice", "Bob");
List<String> sorted = names.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
对Set排序
由于Set本身无序,需要转换为List后排序:
Set<Integer> numbers = new HashSet<>(Arrays.asList(5, 3, 8, 1));
List<Integer> sorted = new ArrayList<>(numbers);
Collections.sort(sorted);
对Map按key或value排序
Map<String, Integer> map = ...;
// 按key排序
List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
entries.sort(Map.Entry.comparingByKey());
// 按value排序
entries.sort(Map.Entry.comparingByValue());
以上方法覆盖了Java中对各种集合类型进行排序的主要场景,可根据具体需求选择合适的方式。







