如何对list进行排序
时间: 2023-07-22 11:04:20 浏览: 59
要对一个Java中的List进行排序,你可以使用`Collections.sort()`方法或使用Java 8中的Stream API。
方法1:使用`Collections.sort()`方法进行排序
```java
List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
Collections.sort(numbers); // 默认升序排序
System.out.println(numbers); // 输出 [1, 2, 5, 8]
```
上述示例中,我们创建了一个包含整数的List,并使用`Collections.sort()`方法对其进行排序。默认情况下,它会按照升序进行排序。
如果你希望进行自定义排序,你可以传递一个实现了`Comparator`接口的自定义比较器给`Collections.sort()`方法。比如,如果你要按照整数的逆序进行排序:
```java
Collections.sort(numbers, Collections.reverseOrder());
System.out.println(numbers); // 输出 [8, 5, 2, 1]
```
方法2:使用Java 8的Stream API进行排序
```java
List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
List<Integer> sortedList = numbers.stream()
.sorted()
.collect(Collectors.toList());
System.out.println(sortedList); // 输出 [1, 2, 5, 8]
```
上述示例中,我们使用Java 8的Stream API对List进行排序。我们通过调用`stream()`方法将List转换为Stream,然后使用`sorted()`方法对元素进行排序,最后通过`collect()`方法将排序后的元素收集到一个新的List中。
这两种方法都可以对List进行排序,你可以根据具体情况选择适合的方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)