
Kotlin collections provide powerful functions that allow developers to write concise and expressive code.
Instead of writing long loops, Kotlin lets you perform complex operations with simple and readable functions.
If you're developing Android apps with Kotlin, you'll frequently use collection functions such as:
map
filter
reduce
forEach
groupBy
This guide provides a quick Kotlin collections cheat sheet with practical examples you can use in real projects.
👉 Developer Tip
Most experienced Kotlin developers rely heavily on these collection functions because they make code shorter and easier to maintain.
Collections in Kotlin allow you to work with groups of data such as:
Lists
Sets
Maps
Example list:
val numbers = listOf(1,2,3,4,5)
From here, Kotlin provides many useful functions to transform or process the data.
The map function transforms each element in a collection.
Example:
val numbers = listOf(1,2,3)
val doubled = numbers.map {
it * 2
}Result:
[2,4,6]
The filter function selects elements that match a condition.
Example:
val numbers = listOf(1,2,3,4,5)
val evenNumbers = numbers.filter {
it % 2 == 0
}Result
[2,4]
forEach is used to iterate through elements.
Example:
numbers.forEach {
println(it)
}Developer insight
Use forEach when you need to perform an action on every element.
reduce combines elements into a single result.
Example:
val numbers = listOf(1,2,3,4)
val sum = numbers.reduce { acc, i ->
acc + i
}Result
10
groupBy groups elements based on a condition.
Example:
val numbers = listOf(1,2,3,4,5)
val grouped = numbers.groupBy {
it % 2 == 0
}Result
{false=[1,3,5], true=[2,4]}
| Function | Purpose |
|---|---|
| map | transform elements |
| filter | select elements |
| forEach | iterate elements |
| reduce | combine values |
| groupBy | group elements |
"어떤 것을 완전히 알려거든 그것을 다른 이에게 가르쳐라."
- Tryon Edwards -