2 回答
TA贡献1852条经验 获得超1个赞
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的Pair tuple实现 AbstractMap.SimpleEntry
TA贡献1847条经验 获得超11个赞
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;}
}
添加回答
举报