Kotlin collections come with dozens of functions that let you transform data in one readable line instead of writing loops. This lesson covers the ones you’ll use every day.
We’ll use this list in the examples:
data class Product(val name: String, val category: String, val price: Int, val inStock: Boolean)
val products = listOf(
Product("Mouse", "Accessories", 599, true),
Product("Keyboard", "Accessories", 1299, false),
Product("Monitor", "Displays", 8999, true),
Product("Webcam", "Accessories", 2499, true),
Product("Laptop", "Computers", 54999, true)
)Page Contents
map: transform each item
// uses the products list from the top of this lesson
fun main() {
println(products.map { it.name })
println(products.map { it.price * 2 })
println(products.mapIndexed { i, p -> "${i + 1}. ${p.name}" })
}Output:
[Mouse, Keyboard, Monitor, Webcam, Laptop] [1198, 2598, 17998, 4998, 109998] [1. Mouse, 2. Keyboard, 3. Monitor, 4. Webcam, 5. Laptop]
filter: keep matching items
// uses the products list from the top of this lesson
fun main() {
println(products.filter { it.price < 2000 }.map { it.name })
println(products.filterNot { it.inStock }.map { it.name })
println(listOf("a", null, "b").filterNotNull())
}Output:
[Mouse, Keyboard] [Keyboard] [a, b]
Chaining
You can combine functions. Each step returns a new list:
// uses the products list from the top of this lesson
fun main() {
val cheapInStock = products
.filter { it.inStock }
.filter { it.price < 5000 }
.sortedBy { it.price }
.map { "${it.name} – ₹${it.price}" }
println(cheapInStock)
}Output:
[Mouse – ₹599, Webcam – ₹2499]
Checking: any, all, none, count
// uses the products list from the top of this lesson
fun main() {
println(products.any { it.price > 50000 })
println(products.all { it.inStock })
println(products.none { it.price < 0 })
println(products.count { it.category == "Accessories" })
}Output:
true false true 3
Finding: find, first, last
// uses the products list from the top of this lesson
fun main() {
println(products.find { it.price > 5000 }?.name)
println(products.firstOrNull { it.category == "Phones" })
println(products.last { it.category == "Accessories" }.name)
}Output:
Monitor null Webcam
find and firstOrNull return null when nothing matches. first { } throws an exception, so use it only when a match must exist.
Numbers: sumOf, average, maxBy, minBy
// uses the products list from the top of this lesson
fun main() {
println(products.sumOf { it.price })
println(products.map { it.price }.average())
println(products.maxBy { it.price }.name)
println(products.minBy { it.price }.name)
}Output:
68395 13679.0 Laptop Mouse
Grouping and splitting: groupBy, partition, chunked
// uses the products list from the top of this lesson
fun main() {
val byCategory = products.groupBy({ it.category }, { it.name })
println(byCategory)
val (available, soldOut) = products.partition { it.inStock }
println("${available.size} available, ${soldOut.size} sold out")
println(products.map { it.name }.chunked(2))
}Output:
{Accessories=[Mouse, Keyboard, Webcam], Displays=[Monitor], Computers=[Laptop]}
4 available, 1 sold out
[[Mouse, Keyboard], [Monitor, Webcam], [Laptop]]flatMap and flatten
fun main() {
val orders = listOf(listOf("Tea", "Biscuits"), listOf("Coffee"), listOf("Tea", "Sandwich"))
println(orders.flatten())
println(orders.flatten().distinct())
val sentences = listOf("learn kotlin", "build apps")
println(sentences.flatMap { it.split(" ") })
}Output:
[Tea, Biscuits, Coffee, Tea, Sandwich] [Tea, Biscuits, Coffee, Sandwich] [learn, kotlin, build, apps]
zip: combine two lists
fun main() {
val names = listOf("Asha", "Ravi", "Meera")
val scores = listOf(88, 92, 79)
println(names.zip(scores))
println(names.zip(scores) { n, s -> "$n scored $s" })
}Output:
[(Asha, 88), (Ravi, 92), (Meera, 79)] [Asha scored 88, Ravi scored 92, Meera scored 79]
reduce and fold
Both combine all the items into one value. fold takes a starting value; reduce uses the first item:
fun main() {
val numbers = listOf(3, 5, 2, 8)
println(numbers.reduce { acc, n -> acc + n })
println(numbers.fold(100) { acc, n -> acc + n })
println(numbers.fold("") { acc, n -> acc + n })
}Output:
18 118 3528
reduce crashes on an empty list. fold is safe, because it always has a starting value.
forEach vs map
forEachdoes something with each item and returns nothing:products.forEach { println(it.name) }.mapbuilds and returns a new list. Don’t usemapjust to print things.
Common mistakes
- Using
first { }when nothing may match: usefirstOrNullorfind. - Long chains on huge lists: each step creates a new list. For very large data, use
asSequence()to process items lazily. - Calling
reduceon a possibly empty list: usefold.
Exercise
From the product list, print the total value of in-stock accessories, and the most expensive item in each category.
// uses the products list from the top of this lesson
fun main() {
val accessoriesValue = products
.filter { it.inStock && it.category == "Accessories" }
.sumOf { it.price }
println("In-stock accessories: ₹$accessoriesValue")
products.groupBy { it.category }
.mapValues { (_, items) -> items.maxBy { it.price }.name }
.forEach { (category, name) -> println("$category: $name") }
}Output:
In-stock accessories: ₹3098 Accessories: Webcam Displays: Monitor Computers: Laptop
FAQ
What is the difference between map and forEach in Kotlin?
map returns a new list of transformed items. forEach just runs code for each item and returns nothing.
What is the difference between fold and reduce?
fold starts from a value you give it and works on empty lists. reduce starts from the first item and throws on an empty list.
What does groupBy return?
A Map from each key to the list of items with that key, for example Map<String, List<Product>>.
