Collections are where Kotlin really shines. Lists, sets, and maps come in two flavors โ read-only and mutable โ and they're packed with powerful operations that let you transform data in elegant ways.
Lists
listOf creates a read-only list. mutableListOf gives you one you can add to or remove from.
fun main() {
val fruits = listOf("Apple", "Banana", "Cherry")
val mutable = mutableListOf("Apple", "Banana")
mutable.add("Cherry")
mutable.remove("Apple")
println(fruits)
println(mutable)
println(fruits[1])
}
Access elements with square brackets or use .get(). Remember: read-only means you can't change the list, but if the items are mutable objects themselves, they can still be modified.
Sets and Maps
Sets hold unique values. Maps hold key-value pairs.
fun main() {
val uniqueNums = setOf(1, 2, 3, 3, 2)
println(uniqueNums)
val scores = mapOf("Alice" to 95, "Bob" to 87)
println(scores["Alice"])
println(scores.getOrDefault("Eve", 0))
}
Sets automatically deduplicate โ notice the repeated values disappear. Maps use to infix function for creating key-value pairs.
Common operations
This is where Kotlin collections really flex. filter, map, and forEach let you process data in one clean chain.
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6)
val evens = numbers.filter { it % 2 == 0 }
val doubled = numbers.map { it * 2 }
val sum = numbers.reduce { acc, n -> acc + n }
println("Evens: $evens")
println("Doubled: $doubled")
println("Sum: $sum")
numbers.forEach { print("$it ") }
}
filter keeps items matching a condition. map transforms each item. forEach does something with each item. reduce combines them into a single value.