在Java中,对列表进行排序有几种常见的方法:
1. 使用`Collections.sort()`方法:
import java.util.Collections;import java.util.List;public class ListSortingExample {public static void main(String[] args) {Listnumbers = List.of(5, 2, 7, 1, 3); Collections.sort(numbers);System.out.println("排序后的列表: " + numbers);}}
2. 使用`List.sort()`方法(Java 8及以上版本):
import java.util.List;public class ListSortingExample {public static void main(String[] args) {Listnumbers = List.of(5, 2, 7, 1, 3); numbers.sort(Integer::compareTo);System.out.println("排序后的列表: " + numbers);}}
3. 使用`Comparator`接口进行自定义排序:

import java.util.ArrayList;import java.util.Comparator;import java.util.List;public class ListSortingExample {public static void main(String[] args) {ListstudentList = new ArrayList<>(); studentList.add(new Student("Alice", 20));studentList.add(new Student("Bob", 18));studentList.add(new Student("Charlie", 22));Comparatorcomparator = Comparator.comparingInt(Student::getAge); Collections.sort(studentList, comparator);System.out.println("排序后的列表: " + studentList);}}
4. 使用Java 8的`Stream` API进行排序:
import java.util.List;import java.util.stream.Collectors;public class ListSortingExample {public static void main(String[] args) {Listnumbers = List.of(5, 2, 7, 1, 3); ListsortedNumbers = numbers.stream().sorted().collect(Collectors.toList()); System.out.println("排序后的列表: " + sortedNumbers);}}
