问题描述
使用Java8 中的Collectors.groupingBy根据一个或多个属性进行分组并格式化(如图)
定义一个"部门类"
@Data
private static class Company {
private String department;/*部门名称*/
private String personName;/*成员名称*/
public Company(String department, String personName) {
this.department = department;
this.personName = personName;
}
}
创建一个Main方法进行测试分组
public static void main(String[] args) {
/*创建List对象测试*/
List<Company> companyList = Arrays.asList(
new Company("北京部门", "张三"),
new Company("上海部门", "李四"),
new Company("北京部门", "王五"));
/*分组逻辑处理*/
if (ObjectUtils.isNotEmpty(companyList)) {
Map<String, List<Company>> collect = companyList.stream()
.collect(Collectors.groupingBy(t -> t.getDepartment()));
String projectMembers = "";
for (String key : collect.keySet()) {
projectMembers += key + ":";
List<Company> personList = collect.get(key);
for (int i = 0; i < personList.size(); i++) {
Company p = personList.get(i);
String f = "、";
if (i == personList.size() - 1) {
f = "。";
}
projectMembers += p.getPersonName() + f;
}
projectMembers += "\r\n";
}
System.out.println(projectMembers);
}
}