猿问

Java分组按列表

class Student {
    List<Integer> grades
    }

我想按年级对学生进行分组,但是如果每个学生只有一个年级,则groupingBy可以工作。还有其他兰巴舞的方法吗?我希望结果像 Map<Integer, List<Student>>


不负相思意
浏览 108回答 2
2回答

小怪兽爱吃肉

Map<Integer, List<Student>> collect = students.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .flatMap(student -> student.grades.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(grade -> new AbstractMap.SimpleEntry<>(grade,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; student)))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.groupingBy(entry -> entry.getKey(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Collectors.mapping(Entry::getValue, Collectors.toList())));因为我没有使用Java的Pair tuple实现 AbstractMap.SimpleEntry

回首忆惘然

groupingBy如果您有所帮助,它将完成此工作:您可能会在Javadoc中为groupingBy找到与此版本等效的版本。final List<Student> students = ...;// @formatter:offstudents.stream()&nbsp; &nbsp; &nbsp; &nbsp; .flatMap(student -> student.grades.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(grade -> new StudentGrade(student, grade)))&nbsp; &nbsp; &nbsp; &nbsp; .collect(groupingBy(StudentGrade::getGrade, mapping(StudentGrade::getStudent, toList())));// @formatter:on现在,您得到一个Map<Integer, List<Student>>。过滤重复项取决于您。您将需要这些导入:import static java.util.stream.Collectors.groupingBy;import static java.util.stream.Collectors.mapping;import static java.util.stream.Collectors.toList;类StudentGrade很简单:class StudentGrade {&nbsp; private final Student student;&nbsp; private final Integer&nbsp; &nbsp;grade;&nbsp; public StudentGrade(Student student, Integer grade) {&nbsp; &nbsp; this.student = student;&nbsp; &nbsp; this.grade = grade;&nbsp; }&nbsp; public Student getStudent() {return student;}&nbsp; public Integer getGrade()&nbsp; &nbsp;{return grade;}}
随时随地看视频慕课网APP

相关分类

Java
我要回答