Kotlin Tutorial · Functional Kotlin and Collections · Lesson 20 of 31
Kotlin Collection Operations
Transform and query collections with map, filter, sortedBy, groupBy, associate, fold, partition and more.
Transforming and filtering
The standard library has a rich set of operations that return new collections, so you rarely write loops.
data class Order(val id: Int, val customer: String, val total: Double, val paid: Boolean)
val orders = listOf(
Order(1, "Ana", 40.0, true), Order(2, "Ben", 15.5, false),
Order(3, "Ana", 22.0, true), Order(4, "Caro", 99.9, true),
)
fun main() {
println(orders.filter { it.paid }.map { it.id })
println(orders.sortedByDescending { it.total }.take(2).map { it.customer })
println(orders.sumOf { it.total })
println(orders.maxBy { it.total }.id)
println(orders.any { !it.paid })
println(orders.map { it.customer }.distinct().joinToString(", "))
}
Output
[1, 3, 4] [Caro, Ana] 177.4 4 true Ana, Ben, Caro
Run this on your computer — see “Get Started” for setup.
Grouping and aggregating
groupBy builds a map of lists, associateBy a map keyed by a property, fold reduces with an initial value,
and partition splits into two lists.
data class Order(val id: Int, val customer: String, val total: Double, val paid: Boolean)
val orders = listOf(
Order(1, "Ana", 40.0, true), Order(2, "Ben", 15.5, false),
Order(3, "Ana", 22.0, true), Order(4, "Caro", 99.9, true),
)
fun main() {
val byCustomer = orders.groupBy { it.customer }
println(byCustomer.mapValues { (_, list) -> list.sumOf { it.total } })
println(orders.associateBy { it.id }[3])
val (paid, unpaid) = orders.partition { it.paid }
println("${paid.size} paid, ${unpaid.size} unpaid")
println(orders.fold(0) { count, o -> if (o.total > 20) count + 1 else count })
println(orders.chunked(2).map { chunk -> chunk.map { it.id } })
}
Output
{Ana=62.0, Ben=15.5, Caro=99.9}
Order(id=3, customer=Ana, total=22.0, paid=true)
3 paid, 1 unpaid
3
[[1, 2], [3, 4]]Run this on your computer — see “Get Started” for setup.
Test yourself
What does groupBy return?
A sorted listA map from each key to the list of elements with that keyA set of keysA pair of lists
Show answer
Answer: A map from each key to the list of elements with that key