import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Demo {
@Data
@AllArgsConstructor
static class Student{
private String name;
private int age;
private String groupCode;
}
public static void main(String[] args) {
Student student0 = new Student("张三", 18, "1");
Student student1 = new Student("李四", 18, "1,2");
Student student2 = new Student("王五", 18, "1,2,3");
Student student3 = new Student("老六", 18, "1,3");
Student student4 = new Student("七八", 18, "2");
Student student5 = new Student("老王", 18, "3");
List<Student> list = Arrays.asList(student0, student1, student2, student3, student4, student5);
Map<String, List<Student>> collect = list.parallelStream().collect(Collectors.groupingBy(Student::getGroupCode));
System.out.println(new Gson().toJson(collect));
}
}
定义一个Student类里面有姓名年龄和分组代码,但是一个学生可能在多个角色,又是升旗手又是班委,groupCode存在一对多关系.想把学生按map分类,但是同时拥有多个角色的学生在多个分类中也应该出现.比如李四groupCode"1,2",那他应该同时出现在分组1和分组2中.如何用lambda实现,或者其他简洁的方法实现分组.