user2101699
user2101699

Reputation: 257

Kotlin flatten + map of nested objects

I have a list of objects that looks like:

data class Classroom(
 val id: Int,
 val name: String,
 val students: List<Student>
)

data class Student(
 val id: Int,
 val name: String,
 val age: Int,
 val gpa: Long,
)

I wanna have a hash map that maps Student.name -> Student of all the students that are in all of the classes (regardless of which student belongs to each class).

My input is a List of Classroom

How can i achieve that elegantly?

Upvotes: 0

Views: 2998

Answers (1)

Adam Millerchip
Adam Millerchip

Reputation: 23091

val studentMap: Map<String, Student> = classrooms
    .flatMap { it.students }
    .associate { student -> student.name to student }
  1. Use flatMap to extract all the students
  2. associate them to name/student pairs

Here is the the setup and test code, that you should have provided in the question.

fun generateClassrooms() : List<Classroom> {
    val classANames = listOf("foo", "bar", "baz")
    val classBNames = listOf("baz", "asdf", "ghjk")
    val classCNames = listOf("asdf", "ghjk", "bar", "qwerty")

    val student = Student(0, "name", 0, 0)
    val classAStudents = classANames.map { student.copy(name = it) }
    val classBStudents = classBNames.map { student.copy(name = it) }
    val classCStudents = classCNames.map { student.copy(name = it) }

    val classroom = Classroom(0, "classroom", emptyList())
    val classA = classroom.copy(students = classAStudents)
    val classB = classroom.copy(students = classBStudents)
    val classC = classroom.copy(students = classCStudents)

    return listOf(classA, classB, classC)
}

fun main() {
    val classrooms = generateClassrooms()
    val studentMap: Map<String, Student> = classrooms
        .flatMap { it.students }
        .associate { student -> student.name to student }

    for (student in studentMap) println(student)
}

Running this produces:

foo=Student(id=0, name=foo, age=0, gpa=0)
bar=Student(id=0, name=bar, age=0, gpa=0)
baz=Student(id=0, name=baz, age=0, gpa=0)
asdf=Student(id=0, name=asdf, age=0, gpa=0)
ghjk=Student(id=0, name=ghjk, age=0, gpa=0)
qwerty=Student(id=0, name=qwerty, age=0, gpa=0)

Upvotes: 3

Related Questions