'How to iterate over a Triple in Kotlin
I have list of three set of values which are related to each other. i.e. Roll Number, Student Name and School Name.
I am using Kotlin Triple to store them. Below is the code:
val studentData = listOf(
Triple(first = "1", second ="Sam", third = "MIT"),
Triple(first = "2", second ="Johnny", third = "SYM"),
Triple(first = "3", second ="Depp", third = "PIT")
)
And now I need to build a function which will accept roll number and will return either student name or school name. Something like below:
fun getStudentDetails(rollNumber: String) : String {
//...
//return student name or school name
}
How to achieve this?
How to traverse the Triple
in most preformat way considering below:
a) the time and space complexity
b) the list of student details can grow large
Solution 1:[1]
Given that rollNumber
is a String
you can just filter the list using firstOrNull
and return the student name or school name:
fun getStudentDetails(rollNumber: String) : String =
studentData.firstOrNull({ (roll, _, _) ->
roll == rollNumber
})?.second ?: "No student with $rollNumber"
The space complexity would be constant, the time complexity is O(n) at the worst case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Commander Tvis |