java stream流 一个字段按照我定义的一个值顺序排序
时间: 2024-10-29 15:23:58 浏览: 45
Java Stream API 提供了一种方便的方式来对集合数据进行处理,包括排序操作。如果你想按照自定义的值对一个字段进行排序,你可以使用 `sorted()` 函数配合 Lambda 表达式。
假设有一个包含自定义对象的列表,比如 `Person` 类,其中有一个 `age` 字段:
```java
class Person {
String name;
int age;
// getters and setters...
}
```
你可以这样做来按年龄排序:
```java
List<Person> people = ...; // 假设这是你的 person 列表
List<Person> sortedByAge = people.stream()
.sorted(Comparator.comparing(Person::getAge)) // 使用 lambda 表达式指定比较规则
.collect(Collectors.toList()); // 收集到新的列表中
```
这里,`Comparator.comparing(Person::getAge)` 用于创建一个比较器,它基于 `Person` 对象的 `age` 属性进行排序。如果想按照降序排列,可以添加 `.reversed()`:
```java
List<Person> sortedDescByAge = people.stream()
.sorted(Comparator.comparing(Person::getAge).reversed())
.collect(Collectors.toList());
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)