简体   繁体   中英

Java groupingBy List

class Student {
    List<Integer> grades
}

I want grouping students by grades but groupingBy would work if each student had only one grade. Is any other lamba way to do it? I expect result like Map<Integer, List<Student>>

groupingBy will do the job if you help it: you might find an equivalent version of this in the Javadoc for 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

Now, you get a Map<Integer, List<Student>> . It is up to you to filter duplicates.

You will need these imports:

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;

Class StudentGrade is simple:

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;}
}
 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())));

Because Java do not have Pair tuple implementation I used AbstractMap.SimpleEntry

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM