stream流分组后过滤
时间: 2025-07-13 16:32:08 浏览: 1
### 使用 Java Stream API 对分组后的数据进行过滤
在 Java 中,`Stream API` 提供了强大的功能来处理集合中的数据。当使用 `Collectors.groupingBy()` 方法对数据进行分组后,可以通过进一步的操作对每组的数据进行过滤或其他处理。
以下是完整的代码示例,展示如何先按照某个字段(如城市)对列表进行分组,然后再对每组内的数据应用过滤条件:
```java
import java.util.*;
import java.util.stream.Collectors;
public class GroupAndFilterExample {
static class Employee {
private String name;
private int age;
private String city;
public Employee(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getCity() {
return city;
}
@Override
public String toString() {
return "Employee{name='" + name + "', age=" + age + ", city='" + city + "'}";
}
}
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Alice", 25, "New York"),
new Employee("Bob", 30, "London"),
new Employee("Charlie", 35, "New York"),
new Employee("David", 40, "Paris"),
new Employee("Eve", 28, "London")
);
// 按照城市分组并过滤年龄大于30岁的员工
Map<String, List<Employee>> groupedFilteredEmployees = employees.stream()
.collect(Collectors.groupingBy(
Employee::getCity,
Collectors.filtering(emp -> emp.getAge() > 30, Collectors.toList())
));
// 打印结果
groupedFilteredEmployees.forEach((city, employeeList) -> {
System.out.println(city + ": " + employeeList);
});
}
}
```
#### 解析
上述代码实现了以下逻辑:
1. **分组**:通过 `Collectors.groupingBy(Employee::getCity)` 将员工按其所在的城市分组[^1]。
2. **过滤**:对于每个城市的分组结果,仅保留年龄超过 30 岁的员工。这里使用了自定义收集器 `Collectors.filtering(predicate, downstream)` 来完成这一操作[^2]。
3. **打印结果**:最终的结果是一个映射表 (`Map`),其中键为城市名称,值为该城市中符合条件的员工列表。
如果需要更复杂的业务逻辑,则可以考虑实现自己的 `Collector` 接口[^3]。
---
###
阅读全文
相关推荐


















