java中的list如何排序
时间: 2024-06-09 10:05:49 浏览: 12
在Java中,可以使用多种方法对List进行排序。其中包括使用Collections类的sort方法、List接口自身的sort方法以及Stream流的sort方法。
方式1:使用Collections类的sort方法对List进行排序。示例代码如下:
```
List<Integer> numList = new ArrayList<>();
numList.add(999);
numList.add(123);
numList.add(456);
numList.add(66);
numList.add(9);
Collections.sort(numList);
System.out.println(numList);
```
方式2:使用List接口自己的sort方法对List进行排序。示例代码如下:
```
List<Integer> numList = new ArrayList<>();
numList.add(999);
numList.add(123);
numList.add(456);
numList.add(66);
numList.add(9);
numList.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
});
System.out.println(numList);
```
方式3:使用Stream流的sort方法对List进行排序。示例代码如下:
```
List<Integer> numList = new ArrayList<>();
numList.add(999);
numList.add(123);
numList.add(456);
numList.add(66);
numList.add(9);
numList.sort((num1, num2) -> num1.compareTo(num2));
System.out.println(numList);
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)