Collections & Operations
Read-only vs mutable
| Read-only | Mutable |
|---|---|
listOf(1, 2, 3) | mutableListOf(1, 2, 3) |
setOf("a", "b") | mutableSetOf() |
mapOf("pen" to 20) | mutableMapOf() |
Prefer read-only collections; make them mutable only where needed. a to b creates a Pair. |
Common operations
| Function | Does |
|---|---|
filter { }, map { } | keep matching items / transform each item |
first { }, firstOrNull { }, find { } | the first match |
any { }, all { }, none { }, count { } | checks and counts |
sum(), sumOf { }, average(), maxOf { }, minByOrNull { } | numbers |
sortedBy { }, sortedByDescending { } | sorted copies |
groupBy { } | a Map<Key, List> |
associateBy { }, associate { } | build maps |
partition { } | two lists: matching and not matching |
take(n), drop(n), chunked(n), windowed(n), zip(other) | slicing and pairing |
flatMap { }, distinct(), joinToString() | flatten, unique, text |
Maps
val prices = mutableMapOf("pen" to 20)
prices["book"] = 350
prices["pen"] // 20 (nullable!)
prices.getOrDefault("bag", 0)
for ((item, price) in prices) …
Sequences: lazy processing
For big data or long chains, asSequence() processes items one at a time and stops early:
(1..1_000_000).asSequence().map { it * 2 }.filter { it % 3 == 0 }.take(5).toList()
Arrays
arrayOf(1, 2) and intArrayOf(1, 2) are fixed-size; use lists in most code.
Example
data class Product(val name: String, val category: String, val price: Int, val inStock: Boolean)
fun main() {
val products = listOf(
Product("Pen", "office", 20, true),
Product("Notebook", "office", 120, true),
Product("Backpack", "travel", 1500, false),
Product("Bottle", "travel", 450, true),
Product("Stapler", "office", 300, true),
)
println(products.filter { it.inStock }.map { it.name })
println("Total stock value: ${products.filter { it.inStock }.sumOf { it.price }}")
println("Most expensive: ${products.maxByOrNull { it.price }?.name}")
println("Any out of stock? ${products.any { !it.inStock }}")
val byCategory = products.groupBy { it.category }
byCategory.forEach { (cat, items) -> println("$cat: ${items.joinToString { it.name }}") }
val (cheap, pricey) = products.partition { it.price < 200 }
println("Cheap: ${cheap.map { it.name }}, pricey: ${pricey.size}")
val priceOf = products.associate { it.name to it.price }
println("Price of Pen: ${priceOf["Pen"]}, Bag: ${priceOf["Bag"] ?: "n/a"}")
val cart = mutableListOf("Pen")
cart += "Bottle"
println(cart)
println((1..1_000_000).asSequence().map { it * 2 }.filter { it % 3 == 0 }.take(5).toList())
println(listOf(1, 2, 3, 4, 5).chunked(2))
}