用java的stream工具,对一个对象类型的list,按某个属性分组,对另外一个属性用逗号拼接字符串。举例:我提供了一个List<Student>集合,按sex属性汇总name属性,输出一个List,list中具体的成员值为,sex="男",name="张三,李四";第二个成员值为,sex="女",name="王五,赵六,黄七"
时间: 2023-05-23 12:07:24 浏览: 722
可以通过如下代码实现:
```java
import java.util.*;
import java.util.stream.*;
public class GroupingAndJoining {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("男", "张三"),
new Student("男", "李四"),
new Student("女", "王五"),
new Student("女", "赵六"),
new Student("女", "黄七")
);
Map<String, List<Student>> groupedStudents = students.stream()
.collect(Collectors.groupingBy(Student::getSex));
List<Student> resultList = new ArrayList<>();
for (Map.Entry<String, List<Student>> entry : groupedStudents.entrySet()) {
String sex = entry.getKey();
List<String> names = entry.getValue().stream()
.map(Student::getName)
.collect(Collectors.toList());
resultList.add(new Student(sex, String.join(",", names)));
}
System.out.println(resultList);
}
}
class Student {
private String sex;
private String name;
public Student(String sex, String name) {
this.sex = sex;
this.name = name;
}
public String getSex() {
return sex;
}
public String getName() {
return name;
}
public String toString() {
return "sex=\"" + sex + "\", name=\"" + name + "\"";
}
}
```
输出结果为:
```text
[sex="男", name="张三,李四", sex="女", name="王五,赵六,黄七"]
```
阅读全文