1

I have a list of Student objects List<Student> allStudents from which I need to find out which student gained how much score per course and task using Java 8 stream API. I came across some older posts like this one but couldn't apply to my problem.

Below are my nested classes:

public class Student{
    private long studentId;
    private List<Course> courses;

    public long getStudentId() {
        return studentId;
    }

    public List<Course> getCourses() {
        return courses;
    }
}

public class Course{
    private long courseId;
    private List<Task> tasks;

    public long getCourseId() {
        return courseId;
    }

    public List<Task> getTasks() {
        return tasks;
    }
}

public class Task{
    private long taskId;
    private List<Assessment> assessments;

    public long getTaskId() {
        return taskId;
    }

    public List<Assessment> getAssessments() {
        return assessments;
    }
}

public class Assessment{
    private String type;
    private double score;

    public String getType() {
        return type;
    }

    public double getScore() {
        return score;
    }
}

Somehow multi level grouping couldn't work for me. Could anyone guide me on this ?

Solubris
  • 3,603
  • 2
  • 22
  • 37

1 Answers1

1

As you mentioned in the old question you referenced, can use the flat map approach where each nesting level is flat mapped down to the level required as follows:

    Map<Triple<Long, Long, Long>, Double> result = allStudents.stream()
            .flatMap(s -> s.getCourses().stream().map(
                    c -> ImmutableTuple.of(s.getStudentId(), c)))
            .flatMap(sc -> sc.get().getTasks().stream().map(
                    t -> ImmutableTuple.of(sc.getFirst(), sc.get().getCourseId(), t)))
            .flatMap(sct -> sct.get().getAssessments().stream().map(
                    a -> ImmutableTuple.of(sct.getFirst(), sct.getSecond(), sct.get().taskId, a.getScore())))
            .collect(Collectors.groupingBy(
                    ImmutableQuadruple::remove,
                    Collectors.summingDouble(ImmutableQuadruple::get)
            ));

Note: This is using tuples from the typedtuples library

Solubris
  • 3,603
  • 2
  • 22
  • 37