stream流 对list进行分组
时间: 2025-02-21 17:00:13 浏览: 35
### 使用Java Stream API对List集合按条件进行分组
在Java中,`Stream API` 和 `Collectors` 类提供了强大的工具来处理集合数据。对于按照特定条件对列表中的对象进行分组的需求,可以通过定义一个分类逻辑并将其应用于流管道内的元素。
下面是一个具体的例子,展示如何基于某个属性(例如部门名称)对员工记录进行分组:
```java
import java.util.*;
import java.util.stream.Collectors;
class Employee {
private String name;
private String departmentName;
public Employee(String name, String departmentName) {
this.name = name;
this.departmentName = departmentName;
}
public String getName() {
return name;
}
public String getDepartmentName() {
return departmentName;
}
}
public class GroupingExample {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Alice", "HR"),
new Employee("Bob", "Engineering"),
new Employee("Charlie", "HR"),
new Employee("David", "Marketing")
);
Map<String, List<Employee>> groupedByDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartmentName));
groupedByDept.forEach((dept, emps) ->
System.out.printf("Department: %s\nEmployees:%s\n", dept, emps));
}
}
```
上述代码创建了一个名为 `groupedByDept` 的映射表,其中键是部门名而值则是属于该部门的所有雇员组成的列表[^1]。
此方法不仅限于简单的字符串匹配;还可以根据更复杂的业务规则来进行分组。只需调整传递给 `groupingBy()` 方法的参数即可适应不同的需求场景。
阅读全文
相关推荐


















