Kotlin Tutorial · Functional Kotlin and Collections · Lesson 19 of 31
Kotlin Collections: List, Set and Map
Read-only and mutable lists, sets and maps, how to create them, and how to access their elements.
Read-only vs mutable
listOf, setOf and mapOf create read-only collections; mutableListOf, mutableSetOf and
mutableMapOf create ones you can change. Prefer read-only types in function signatures.
fun main() {
val fruits = listOf("apple", "banana", "apple")
println(fruits[1])
println(fruits.size)
println(fruits.toSet()) // duplicates removed
println(fruits.getOrNull(10)) // safe access
val cart = mutableListOf("mug")
cart += "teapot"
cart.add(0, "kettle")
cart.remove("mug")
println(cart)
}
Output
banana 3 [apple, banana] null [kettle, teapot]
Run this on your computer — see “Get Started” for setup.
Maps
"key" to value builds a pair. map[key] returns a nullable value; getOrElse and getOrPut handle missing
keys. Iterate with destructuring: for ((key, value) in map).
fun main() {
val prices = mapOf("mug" to 12.0, "teapot" to 30.0)
println(prices["mug"])
println(prices["spoon"])
println(prices.getOrElse("spoon") { 0.0 })
val stock = mutableMapOf<String, Int>()
for (item in listOf("mug", "mug", "teapot")) {
stock[item] = stock.getOrPut(item) { 0 } + 1
}
for ((item, count) in stock) println("$item: $count")
}
Output
12.0 null 0.0 mug: 2 teapot: 1
Run this on your computer — see “Get Started” for setup.
Test yourself
Which function creates a list you can add elements to?
listOf()mutableListOf()arrayOf()setOf()
Show answer
Answer: mutableListOf()