public class CollectProblem { public static void main(String[] args) { Stream<Student> studentStream = Stream.of( new Student(2, 3, "小明", 80), new Student(3, 1, "小王", 90), new Student(1, 2, "小强", 100), new Student(3, 1, "小红", 90), new Student(1, 2, "小黄", 100), new Student(2, 3, "小黑", 80), new Student(1, 2, "小军", 100), new Student(2, 3, "小乔", 80), new Student(3, 1, "小林", 90)); Map<Integer, Map<Integer, List<Student>>> studentByGradeAndClass = studentStream.collect( Collectors.groupingBy(Student::getGradeId, Collectors.groupingBy(Student::getClassId))); studentByGradeAndClass.forEach((k, m) -> { System.out.print("Grade" + k + " "); m.forEach((key, value) -> System.out.println("Class" + key + " = " + value)); }); } } class Student { private int gradeId; private int classId; private String name; private int score; public Student(int gradeId, int classId, String name, int score) { this.gradeId = gradeId; this.classId = classId; this.name = name; this.score = score; } public int getGradeId() { return gradeId; } public int getClassId() { return classId; } public String getName() { return name; } public int getScore() { return score; } @Override public String toString() { return "Name:" + getName() + " " + "Score: " + getScore(); } }
输出:
Grade1 Class2 = [Name:小强 Score: 100, Name:小黄 Score: 100, Name:小军 Score: 100] Grade2 Class3 = [Name:小明 Score: 80, Name:小黑 Score: 80, Name:小乔 Score: 80] Grade3 Class1 = [Name:小王 Score: 90, Name:小红 Score: 90, Name:小林 Score: 90]
强大,有深度。
后面来的同学,尝试按照成绩,不及格,及格,良好,优秀来分个组,这是业务真实又简单的需求
Sign in to make a reply
xian_wen
输出: