Kotlin Collections
Working with lists, sets, and maps
Lists
val numbers = listOf(1, 2, 3) # immutable list
val mutable = mutableListOf(1, 2) # mutable list
mutable.add(3) # add element
mutable.remove(1) # remove element
numbers[0] # access by index
List Operations
numbers.size # get size
numbers.first() # first element
numbers.last() # last element
numbers.isEmpty() # check if empty
numbers.contains(2) # check if contains
Sets
val unique = setOf(1, 2, 3) # immutable set
val mutableSet = mutableSetOf(1, 2) # mutable set
mutableSet.add(3) # add element
Maps
val ages = mapOf("John" to 30, "Jane" to 25) # immutable map
val mutableMap = mutableMapOf("John" to 30) # mutable map
mutableMap["Bob"] = 35 # add/update
ages["John"] # get value (nullable)
Collection Functions
numbers.filter { it > 1 } # filter elements
numbers.map { it * 2 } # transform elements
numbers.forEach { println(it) } # iterate
numbers.any { it > 2 } # check if any match
numbers.all { it > 0 } # check if all match