Skip to content

Beginner: Kotlin · Classes, objects and collections · topic 12 of 50 · 25 min

Collections: List, Set and Map

Explanation

Kotlin has three main collections: List (ordered, may repeat), Set (unique items) and Map (key-value pairs). Each comes in a read-only form (listOf, setOf, mapOf) and a mutable form (mutableListOf, mutableSetOf, mutableMapOf). Read-only means you cannot change it through that reference, which is not quite the same as immutable.

Why collections?

Apps rarely deal with one value. A cart has many items, a class has many students, a city has many pin codes. A collection holds many values of one type in a single variable. Choosing the right one makes code simpler and faster.

CollectionKeeps order?Duplicates?Good for
List<T>YesAllowedCart items, messages, search results
Set<T>Insertion order for the default setOfNoUnique tags, visited pages
Map<K, V>Insertion order for the default mapOfKeys uniqueLookup by id: roll number → name

Lists

kotlin
fun main() {
    val cities = listOf("Chennai", "Madurai", "Coimbatore")   // read-only
    println(cities[0])              // Chennai
    println(cities.size)            // 3
    println("Madurai" in cities)    // true
    println(cities.getOrNull(9))    // null instead of a crash

    val cart = mutableListOf("milk", "bread")                  // mutable
    cart.add("eggs")
    cart.remove("bread")
    cart[0] = "curd"
    println(cart)                   // [curd, eggs]
}
list[i] throws IndexOutOfBoundsException for a bad index; getOrNull returns null instead.

Positions in a list start at 0, so the first item is cities[0] and the last is cities[cities.size - 1], or simply cities.last(). The in operator checks whether a value is present anywhere in the list.

Sets

kotlin
val tags = mutableSetOf("veg", "spicy", "veg")
println(tags)              // [veg, spicy]: the duplicate is ignored
println(tags.add("spicy")) // false: already there
Sets answer "is this present?" quickly and never hold duplicates.

Maps

kotlin
fun main() {
    val pinToCity = mapOf("600001" to "Chennai", "110001" to "New Delhi")
    println(pinToCity["600001"])               // Chennai
    println(pinToCity["999999"])               // null: missing key
    println(pinToCity.getOrDefault("999999", "Unknown"))

    val stock = mutableMapOf("rice" to 40, "dal" to 25)
    stock["rice"] = 35                          // update
    stock["sugar"] = 10                         // add
    for ((item, qty) in stock) println("$item: $qty")
}
a to b creates a pair. map[key] returns a nullable value because the key may be missing.

Arrays versus lists

Kotlin also has Array<T> (arrayOf), a fixed-size container you mostly meet when calling Java APIs or using vararg. In everyday Kotlin and Android code, prefer List and MutableList: they have more helpful functions, work better with Compose and are what most libraries expect.

Creating empty collections

When a collection starts empty, the compiler cannot guess the item type from values, so you give it: mutableListOf<String>(), emptyList<Int>(), mutableMapOf<String, Int>(). Forgetting the type gives the error "Not enough information to infer type variable T".

Read-only is not immutable

List<T> is a read-only view: it has no add or remove functions. But if the same list object is also referenced as a MutableList somewhere else, it can still change behind your back. For UI state in Android, expose read-only types (List) and keep the mutable one private inside the class that owns it.

kotlin
class Cart {
    private val _items = mutableListOf<String>()
    val items: List<String> get() = _items       // others can read, not change

    fun add(item: String) { _items.add(item) }
}
This private-mutable, public-read-only pattern is very common in Android ViewModels.
Think of it like this: A List is like a queue at a ticket counter: order matters and the same person can appear twice if they rejoin. A Set is like a guest list: each name once. A Map is like a phone's contacts: you look up a number by a name.

Common mistakes

  • Trying to add to a listOf(...) list: there is no add function. Use mutableListOf.
  • Using list[i] with untrusted indexes. Use getOrNull(i).
  • Forgetting that map[key] can be null. Handle it with ?: or getOrDefault.
  • Exposing a MutableList publicly so any code can change it. Expose List instead.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Collections: List, Set and Map · 1/6

List | Set | Map

Collections hold many values. Kotlin has three main ones: List, Set and Map.

Prefer a video by a teacher? Find free videos on “kotlin collections list set map mutable tutorial” on YouTube ↗

In real life: Students by roll number

A school attendance app stores students in a Map from roll number to name, so the teacher can look up any student instantly. Today's attendance is a Set of roll numbers (each student marked once), and the order of arrival is a List. Three collections, each chosen for its job.

kotlin
fun main() {
    val students = mapOf(1 to "Aarav", 2 to "Diya", 3 to "Kabir")
    val present = mutableSetOf<Int>()
    val arrivalOrder = mutableListOf<Int>()
    for (roll in listOf(2, 3, 2)) {           // Diya scanned her card twice
        if (present.add(roll)) arrivalOrder.add(roll)
    }
    val absent = students.keys - present
    println(arrivalOrder.map { students[it] })   // [Diya, Kabir]
    println(absent.map { students[it] })         // [Aarav]
}
Set.add returns false for the duplicate scan, so arrival order is not repeated.

Practice (0/3 done)

Task 1 · Question

What does this print? val s = mutableSetOf(1, 2, 2, 3) s.add(3) println(s.size)

Task 2 · Question

val m = mapOf("a" to 1) What is the type of m["b"]?

Task 3 · Practice

Build a tiny phone book: a mutableMapOf<String, String> from name to number. Add four contacts, update one, remove one, print all sorted by name, and look up a missing name with getOrDefault. Then keep a Set of favourite names and print only favourites that exist in the map.

Quick quiz

Question 1

1.Which collection cannot contain duplicates?

Question 2

2.Which function creates a list you can add to?

Question 3

3.What does "a" to 1 create?

Question 4

4.Why expose List instead of MutableList from a class?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which collection cannot contain duplicates?

Answer: Set

Sets store unique elements.

Which function creates a list you can add to?

Answer: mutableListOf

Mutable collections have add and remove.

What does "a" to 1 create?

Answer: A Pair

to is an infix function that creates a Pair.

Why expose List instead of MutableList from a class?

Answer: So outside code cannot change the data directly

The owner controls changes; others only read.

Which collection keeps only unique values?Related

Answer: Set

Sets ignore duplicates.

From Control flow and collections

Which interface does NOT extend Collection?Related

Answer: Map

Map is a separate hierarchy.

From Collections overview and List

Which operation turns List<Order> into Map<String, List<Order>>?Related

Answer: groupBy

groupBy collects items under each key.

From Collection operations

What is the type of [...]int{1, 2, 3}?Related

Answer: [3]int

... asks the compiler to count the elements, so it is an array of length 3.

From Arrays and slices

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Classes, objects and collections” before its exam: Collection operations.
  2. Module 3 exam: Classes, objects and collections · 14 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Coroutines and Flow. 50 topics left in the course before the final exam.

← Previous: Inheritance and interfaces