Kotlin collections and higher-order functions
Kotlin's standard library offers many functions that take a lambda and work on a whole collection. filter keeps matching elements, map transforms each element, and groupBy splits a list into a map by a key. sumOf adds up a computed value, partition splits a list into two by a condition, and fold combines all elements into one value starting from an initial value. Inside a lambda with one parameter, the implicit name it refers to the element.
Kotlin
data class Person(val name: String, val age: Int, val city: String)
fun main() {
val people = listOf(
Person("Ada", 36, "London"),
Person("Bo", 25, "Paris"),
Person("Cy", 41, "London"),
Person("Di", 25, "Paris"),
)
println(people.filter { it.age > 30 }.map { it.name })
println(people.groupBy { it.city }.mapValues { (_, list) -> list.size })
println(people.sumOf { it.age })
println(people.sortedWith(compareBy({ it.age }, { it.name })).map { it.name })
println(people.maxByOrNull { it.age }?.name)
println(people.partition { it.city == "London" }.let { (london, others) -> london.size to others.size })
println((1..5).fold(1) { product, n -> product * n })
}