Java分组按列表

时间:2018-07-13 18:45:59

标签: java

class Student {
    List<Integer> grades
}

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

2 个答案:

答案 0 :(得分:0)

groupingBy将帮助您完成工作:您可能会在Javadoc中找到groupingBy的等效版本。

final List<Student> students = ...;
// @formatter:off
students.stream()
        .flatMap(student -> student.grades.stream()
                                          .map(grade -> new StudentGrade(student, grade)))
        .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 {
  private final Student student;
  private final Integer   grade;
  public StudentGrade(Student student, Integer grade) {
    this.student = student;
    this.grade = grade;
  }
  public Student getStudent() {return student;}
  public Integer getGrade()   {return grade;}
}

答案 1 :(得分:0)

 Map<Integer, List<Student>> collect = students.stream()
                                                  .flatMap(student -> student.grades.stream()
                                                                                    .map(grade -> new AbstractMap.SimpleEntry<>(grade,
                                                                                            student)))
                                                  .collect(Collectors.groupingBy(entry -> entry.getKey(),
                                                          Collectors.mapping(Entry::getValue, Collectors.toList())));

因为Java没有我使用AbstractMap.SimpleEntry的Pair tuple实现