article banner

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.

Playground

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() ) } }