stream流list对象排序
时间: 2023-11-07 12:51:12 浏览: 96
Stream可以通过使用sorted方法对列表对象进行排序。可以根据指定的字段进行单字段排序,也可以根据多个字段进行排序。
1. 对象单字段排序:
示例代码:
```java
List<People> peopleList = ...; // 假设已存在一个People对象的列表
peopleList = peopleList.stream()
.sorted(Comparator.comparing(People::getJgId))
.collect(Collectors.toList());
```
以上代码将根据People对象的jgId字段进行升序排序。
2. 对象多字段排序:
示例代码:
```java
List<People> peopleList = ...; // 假设已存在一个People对象的列表
peopleList = peopleList.stream()
.sorted(Comparator.comparing(People::getJgId)
.thenComparing(People::getName)
.thenComparing(People::getAge))
.collect(Collectors.toList());
```
以上代码将根据People对象的jgId字段进行升序排序,当jgId相同时再根据name字段进行升序排序,当name相同时再根据age字段进行升序排序。
3. 倒序排序:
示例代码:
```java
List<People> peopleList = ...; // 假设已存在一个People对象的列表
peopleList = peopleList.stream()
.sorted(Comparator.comparing(People::getJgId).reversed())
.collect(Collectors.toList());
```
以上代码将根据People对象的jgId字段进行降序排序。
请根据你的需求选择适合的排序方式,并将其应用于你的列表对象。
阅读全文
相关推荐


















