Kotlin Collections
Work with List, Set, and Map. Use functional operators like filter, map, sortedBy, forEach, find, any, all, and chain operations for concise data transformations.
Collections Overview
Kotlin's standard library provides three main collection types:
- List — ordered sequence of elements (can have duplicates)
- Set — unique elements, no specific order
- Map — key-value pairs, keys are unique
Each type has an immutable version (read-only) and a mutable version (can be modified).
Lists: listOf vs mutableListOf
Create lists using factory functions:
fun main() {
// Immutable — cannot add/remove items
val fruits = listOf("Apple", "Banana", "Cherry")
println(fruits[0]) // Apple
println(fruits.size) // 3
// Mutable — can modify
val scores = mutableListOf(10, 20, 30)
scores.add(40)
scores.removeAt(0) // remove index 0
println(scores) // [20, 30, 40]
}