Exercise: Optimize collection processing
Function getPassingSurnames
has 5 processing steps, but we can easily transform it into 2 simple steps using the functions you know already. Do it. Here is how the function looks like:
fun List<StudentJson>.getPassingSurnames(): List<String> =
this.filter { it.result >= 50 }
.filter { it.pointsInSemester >= 15 }
.map { it.surname }
.filter { it != null }
.map { it!! }
This problem can either be solved in the below playground or you can clone kotlin-exercises project and solve it locally. In the project, you can find code template for this exercise in functional/collections/PassingSurnames.kt. You can find there starting code and unit tests.
Once you are done with the exercise, you can check your solution here.
import junit.framework.TestCase.assertEquals
import org.junit.Test
data class StudentJson(
val name: String?,
val surname: String?,
val result: Double,
val pointsInSemester: Int
)
fun List<StudentJson>.getPassingSurnames(): List<String> =
this.filter { it.result >= 50 }
.filter { it.pointsInSemester >= 15 }
.map { it.surname }
.filter { it != null }
.map { it!! }
class PassingSurnamesTest {
@Test
fun `should return passing surnames`() {
val students = listOf(
StudentJson("John", "Smith", 60.0, 20),
StudentJson("Jane", "Doe", 45.0, 20),
StudentJson("Ivan", "Ivanov", 60.0, 10),
StudentJson("John", "Doe", 30.0, 10),
StudentJson("Jake", "Simonson", 80.0, 20),
)
assertEquals(
listOf("Smith", "Simonson"),
students.getPassingSurnames()
)
}
}
Marcin Moskala is a highly experienced developer and Kotlin instructor as the founder of Kt. Academy, an official JetBrains partner specializing in Kotlin training, Google Developers Expert, known for his significant contributions to the Kotlin community. Moskala is the author of several widely recognized books, including "Effective Kotlin," "Kotlin Coroutines," "Functional Kotlin," "Advanced Kotlin," "Kotlin Essentials," and "Android Development with Kotlin."
Beyond his literary achievements, Moskala is the author of the largest Medium publication dedicated to Kotlin. As a respected speaker, he has been invited to share his insights at numerous programming conferences, including events such as Droidcon and the prestigious Kotlin Conf, the premier conference dedicated to the Kotlin programming language.