The Kotlin standard library provides built-in support for the dataset group by operation. In this recipe, we are going to explore how to use it.
Let's assume we are working with the following types:
class Course(val name: String, val lecturer: Lecturer, val isPaid: Boolean = false)
class Student(val name: String, val courses: List<Course>)
class Lecturer(val name: String)
We also have a getStudents(): List<Student> function that returns a list of all the students from the database.
Given the getStudents(): List<Student> function, we are going to implement the getCoursesWithSubscribedStudents(): Map<Course, List<Student>> function responsible for extracting the map of all the courses students are subscribed to, and the list of students subscribed to each of the courses.