stream 过滤重复的值 按某个字段排序
时间: 2024-10-20 15:03:40 浏览: 40
在Java中,`Stream` API是一个强大的工具,用于处理集合数据。如果你想过滤掉流中的重复值并按某个字段对元素进行排序,可以使用以下步骤:
1. **过滤重复值**:
使用`distinct()`方法可以去除流中的重复元素。例如,如果你有一个整数列表`List<Integer>`,你可以这样做:
```java
List<Integer> uniqueValues = values.stream()
.distinct() // 去除重复
.collect(Collectors.toList());
```
2. **按字段排序**:
对于有自定义比较规则的对象,你可以通过传递一个`Comparator`到`sorted()`方法来指定排序依据。假设你有一个包含自定义类`Person`的列表,`Person`类有一个`age`字段,你可以按年龄排序:
```java
class Person {
int age;
// ...其他属性...
}
List<Person> sortedPeople = people.stream()
.sorted(Comparator.comparing(Person::getAge)) // 按age字段排序
.collect(Collectors.toList());
```
如果你想保持原始列表不变,可以创建一个新的排序后的列表。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](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://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)