最近在写一个需求分组后拼接字段,在页面展示。我本在sql层面实现了,用的group by分组 group_concat函数拼接字段。但是被reivew时被告知不能用group_concat函数,复杂操作需要业务层进行。就写了java去实现 group by + group_concat的功能 业务场景脱敏后如下: 根据姓名分组,分组后多个年龄和爱好用“,”拼接 public static void main(String[] args) { List<Student> list = new ArrayList<>(); Student a = new Student("张三", "12", "足球"); Student b = new Student("张三", "16", "篮球"); Student c = new Student("王五", "17", "排球"); Student d = new Student("李四", "13", "皮球"); Student e = new Student("王五", "12", "水球"); list.add(a); list.add(b); list.add(c); list.add(d); list.add(e); List<Student> stList = list.stream() .collect(groupingBy(Student::getName)) .entrySet() .stream() .map(stEntity -> { // 去重用set即可 List<String> ages = new ArrayList<>(); List<String> hobbys = new ArrayList<>(); stEntity.getValue().stream() .peek(st -> ages.add(st.getAge())) .forEach(st -> hobbys.add(st.getHobby())); return new Student(stEntity.getKey(), String.join(",", ages), String.join(",", hobbys)); }) .collect(Collectors.toList()); System.out.println(stList); } } class Student{ private String name; private String age; private String hobby; public Student(String name, String age, String hobby) { this.name = name; this.age = age; this.hobby = hobby; } public String getName() { return name; } public String getAge() { return age; } public String getHobby() { return hobby; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", hobby='" + hobby + '\'' + '}'; }
结果如下: