本文在 CSDN 同步更新
最近,项目开发时遇到一个问题。根据业务要求,前端给后端上送的参数是一个列表(如List
class Dto{ String classId; List<Student> list; }
public static void testStreamGroup(){ List<Student> stuList = new ArrayList<Student>(); Student stu1 = new Student("10001", "孙权", "1000101", 16, '男'); Student stu2 = new Student("10001", "曹操", "1000102", 16, '男'); Student stu3 = new Student("10002", "刘备", "1000201", 16, '男'); Student stu4 = new Student("10002", "大乔", "1000202", 16, '女'); Student stu5 = new Student("10002", "小乔", "1000203", 16, '女'); Student stu6 = new Student("10003", "诸葛亮", "1000301", 16, '男'); stuList.add(stu1); stuList.add(stu2); stuList.add(stu3); stuList.add(stu4); stuList.add(stu5); stuList.add(stu6); Map<String, List<Student>> collect = stuList.stream().collect(Collectors.groupingBy(Student::getClassId)); for(Map.Entry<String, List<Student>> stuMap:collect.entrySet()){ String classId = stuMap.getKey(); List<Student> studentList = stuMap.getValue(); System.out.println("classId:"+classId+",studentList:"+studentList.toString()); } }
classId:10002,studentList:[Student [classId=10002, name=刘备, studentId=1000201, age=16, sex=男], Student [classId=10002, name=大乔, studentId=1000202, age=16, sex=女], Student [classId=10002, name=小乔, studentId=1000203, age=16, sex=女]] classId:10001,studentList:[Student [classId=10001, name=孙权, studentId=1000101, age=16, sex=男], Student [classId=10001, name=曹操, studentId=1000102, age=16, sex=男]] classId:10003,studentList:[Student [classId=10003, name=诸葛亮, studentId=1000301, age=16, sex=男]]
从上面的数据可以看出来,stuList被分成了三个组,每个组的key都是classId,而每个classId都对应一个学生列表,这样就很轻松地实现了数据的分离;此时,无论需要对数据进行怎样的处理都会很容易。
欢迎关注我的微信公众号: 一辈子的码农先生 ,接下来会有非常多的干货总结,这也是我对自己几年工作的一种总结和交代。谢谢大家!
Previous
经典排序之插入排序