Kotlin Collection Operations
Kotlin collections come with a huge toolbox of functions that take a lambda and return a new result: transform with map, select with filter, aggregate with sumOf or fold, group with groupBy… Chaining them lets you describe what you want instead of writing loops that say how.
All examples in this chapter use this small data set:
data class Sale(val product: String, val category: String, val qty: Int, val price: Double)map and filter
map transforms every element; filter keeps the elements for which the lambda returns true. Inside a single-parameter lambda, the element is called it.
fun main() {
val numbers = listOf(3, 8, 1, 12, 7, 10)
println(numbers.map { it * 2 })
println(numbers.filter { it > 5 })
println(numbers.filter { it % 2 == 0 }.map { "#$it" })
println(numbers.filterNot { it > 5 })
println(listOf("1", "x", "3").mapNotNull { it.toIntOrNull() })
}[6, 16, 2, 24, 14, 20]
[8, 12, 7, 10]
[#8, #12, #10]
[3, 1]
[1, 3]
Searching and checking
| Function | Returns |
|---|---|
first { … } / firstOrNull { … } |
first match (throws / null if none) |
find { … } |
same as firstOrNull |
any { … } / all { … } / none { … } |
Boolean |
count { … } |
number of matches |
indexOfFirst { … } |
index or -1 |
fun main() {
val words = listOf("tree", "sky", "river", "stone", "sun")
println(words.first { it.startsWith("s") })
println(words.find { it.length > 10 })
println(words.any { it.length == 3 })
println(words.all { it.isNotEmpty() })
println(words.count { 'r' in it })
}sky
null
true
true
2
Aggregating
data class Sale(val product: String, val category: String, val qty: Int, val price: Double)
fun main() {
val sales = listOf(
Sale("Pen", "office", 10, 1.5),
Sale("Mug", "kitchen", 2, 8.0),
Sale("Pad", "office", 4, 3.0),
Sale("Pan", "kitchen", 1, 25.0)
)
println(sales.sumOf { it.qty })
println(sales.sumOf { it.qty * it.price })
println(sales.maxBy { it.price }.product)
println(sales.minOf { it.price })
println(sales.map { it.qty }.average())
}17
68.0
Pan
1.5
4.25
Sorting
fun main() {
val people = listOf("Zoe" to 31, "Adam" to 25, "Mia" to 31, "Lee" to 19)
println(people.sortedBy { it.second })
println(people.sortedByDescending { it.second }.map { it.first })
println(people.sortedWith(compareBy({ -it.second }, { it.first })))
println(listOf(5, 2, 9).sorted() + listOf(5, 2, 9).sortedDescending())
}[(Lee, 19), (Adam, 25), (Zoe, 31), (Mia, 31)]
[Zoe, Mia, Adam, Lee]
[(Mia, 31), (Zoe, 31), (Adam, 25), (Lee, 19)]
[2, 5, 9, 9, 5, 2]
sortedBy is stable: Zoe and Mia (both 31) keep their original order.
Grouping and associating
data class Sale(val product: String, val category: String, val qty: Int, val price: Double)
fun main() {
val sales = listOf(
Sale("Pen", "office", 10, 1.5),
Sale("Mug", "kitchen", 2, 8.0),
Sale("Pad", "office", 4, 3.0),
Sale("Pan", "kitchen", 1, 25.0)
)
val byCategory = sales.groupBy { it.category }
for ((cat, list) in byCategory) {
println("$cat: ${list.map { it.product }}")
}
val revenue = sales.groupBy { it.category }
.mapValues { (_, list) -> list.sumOf { it.qty * it.price } }
println(revenue)
println(sales.associate { it.product to it.qty })
println(sales.partition { it.price < 5 }.first.map { it.product })
}office: [Pen, Pad]
kitchen: [Mug, Pan]
{office=27.0, kitchen=41.0}
{Pen=10, Mug=2, Pad=4, Pan=1}
[Pen, Pad]
fold and reduce
fold walks through the collection carrying an accumulator that starts at a value you choose. reduce is the same but starts with the first element.
fun main() {
val nums = listOf(1, 2, 3, 4)
println(nums.fold(0) { acc, n -> acc + n })
println(nums.fold(1) { acc, n -> acc * n })
println(nums.reduce { acc, n -> acc * 10 + n })
println(listOf("a", "b", "c").fold("") { acc, s -> s + acc })
}10
24
1234
cba
More useful functions
| Function | Example | Result |
|---|---|---|
take(n) / drop(n) |
listOf(1,2,3).take(2) |
[1, 2] |
distinct() |
listOf(1,1,2).distinct() |
[1, 2] |
flatMap { } |
listOf("ab","c").flatMap { it.toList() } |
[a, b, c] |
zip |
listOf(1,2) zip listOf("a","b") |
[(1, a), (2, b)] |
chunked(n) |
(1..5).toList().chunked(2) |
[[1, 2], [3, 4], [5]] |
windowed(n) |
listOf(1,2,3).windowed(2) |
[[1, 2], [2, 3]] |
joinToString |
listOf(1,2).joinToString("-") |
"1-2" |
Tip: Each step creates a new list. For long chains on huge collections, consider
asSequence()— see the Sequences chapter.
Test yourself
What does listOf(1, 2, 3).map { it * it } return?
- [1, 2, 3]
- [1, 4, 9]
- 14
- [2, 4, 6]
Which function splits a list into two lists (matching / not matching)?
- groupBy
- chunked
- partition
- filter
What is listOf(2, 3, 4).fold(10) { acc, n -> acc + n }?
- 9
- 19
- 24
- 10