TExcelTAD
Home › Kotlin › Kotlin Collections

Kotlin Collections

Collections hold groups of values. Kotlin's standard library has three main kinds — List, Set and Map — and each comes in two flavours: read-only and mutable. That split is one of Kotlin's best ideas: when a function receives a List, you know it won't add or remove items behind your back.

Kind Read-only Mutable Created with
ordered, duplicates allowed List<T> MutableList<T> listOf, mutableListOf
unique elements Set<T> MutableSet<T> setOf, mutableSetOf
key → value pairs Map<K, V> MutableMap<K, V> mapOf, mutableMapOf

Lists

A list keeps elements in order and allows duplicates. Elements are accessed by index:

kotlin · try it yourself
fun main() {
    val days = listOf("Mon", "Tue", "Wed")
    println(days[1])
    println(days.size)
    println(days.first() + "/" + days.last())
    println("Wed" in days)
    println(days.indexOf("Tue"))
    println(days.getOrNull(7))
}
Tue
3
Mon/Wed
true
1
null

A read-only list has no add or remove. For a list you can change, use mutableListOf:

kotlin · try it yourself
fun main() {
    val todo = mutableListOf("buy milk", "call mum")
    todo.add("water plants")
    todo.add(0, "wake up")       // insert at index 0
    todo.remove("call mum")
    todo[1] = "buy oat milk"     // replace
    println(todo)
    println(todo.size)
}
[wake up, buy oat milk, water plants]
3

Sets

A set keeps each element only once. setOf preserves insertion order when iterating; equality ignores order.

kotlin · try it yourself
fun main() {
    val tags = mutableSetOf("kotlin", "android", "kotlin", "jvm")
    println(tags)
    println(tags.size)
    println(tags.add("jvm"))      // false - already present
    println(tags.add("ktor"))     // true

    val a = setOf(1, 2, 3, 4)
    val b = setOf(3, 4, 5)
    println(a union b)
    println(a intersect b)
    println(a subtract b)
}
[kotlin, android, jvm]
3
false
true
[1, 2, 3, 4, 5]
[3, 4]
[1, 2]

Maps

A map stores values under unique keys. "key" to value creates a Pair, the natural way to write map entries:

kotlin · try it yourself
fun main() {
    val prices = mutableMapOf("apple" to 0.5, "bread" to 2.2)
    prices["cheese"] = 4.8          // add
    prices["apple"] = 0.45          // update
    prices.remove("bread")

    println(prices)
    println(prices["cheese"])
    println(prices["caviar"])                 // null - no such key
    println(prices.getOrDefault("caviar", 0.0))
    println(prices.keys)
    println(prices.values)

    for ((item, price) in prices) println("$item costs $price")
}
{apple=0.45, cheese=4.8}
4.8
null
0.0
[apple, cheese]
[0.45, 4.8]
apple costs 0.45
cheese costs 4.8

mapOf and mutableMapOf keep insertion order (they're backed by LinkedHashMap). Use sortedMapOf or toSortedMap() for key order.

Read-only is not immutable

A List variable may point to a list that someone else can still modify through a MutableList reference. Read-only means you can't change it through this reference:

kotlin · try it yourself
fun main() {
    val source = mutableListOf(1, 2)
    val view: List<Int> = source
    source.add(3)
    println(view)
}
[1, 2, 3]

Use toList() to take an independent copy if you need a snapshot.

Building and converting

kotlin · try it yourself
fun main() {
    val squares = List(5) { it * it }
    val letters = buildList {
        add('a')
        addAll(listOf('b', 'c'))
    }
    println(squares)
    println(letters)
    println(listOf(3, 1, 3, 2).toSet())
    println(listOf("a" to 1, "b" to 2).toMap())
    println(mutableListOf(1, 2).toList())
}
[0, 1, 4, 9, 16]
[a, b, c]
[3, 1, 2]
{a=1, b=2}
[1, 2]

Tip: Default to read-only collections (listOf, setOf, mapOf) and expose read-only types from your classes. Use mutable versions locally while building a result.

Test yourself

Which function creates a list you can add elements to?

  1. listOf
  2. arrayListOf only
  3. mutableListOf
  4. setOf

What does mapOf("a" to 1)["b"] return?

  1. 0
  2. null
  3. An exception
  4. "b"

What is setOf(1, 2, 2, 3).size?

  1. 4
  2. 3
  3. 2
  4. 1