Beginner: Kotlin · Classes, objects and collections · topic 12 of 50 · 25 min
Collections: List, Set and Map
Explanation
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.
| Collection | Keeps order? | Duplicates? | Good for |
|---|---|---|---|
| List<T> | Yes | Allowed | Cart items, messages, search results |
| Set<T> | Insertion order for the default setOf | No | Unique tags, visited pages |
| Map<K, V> | Insertion order for the default mapOf | Keys unique | Lookup by id: roll number → name |
Lists
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]
}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
val tags = mutableSetOf("veg", "spicy", "veg")
println(tags) // [veg, spicy]: the duplicate is ignored
println(tags.add("spicy")) // false: already thereMaps
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")
}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.
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) }
}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
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.
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]
}Practice (0/3 done)
What does this print? val s = mutableSetOf(1, 2, 2, 3) s.add(3) println(s.size)
val m = mapOf("a" to 1) What is the type of m["b"]?
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Collection operationsClasses, objects and collections · same module
- Data, enum and sealed classes, and objectsClasses, objects and collections · same module
- Control flow and collectionsFlutter and Dart · Dart basics
- Collections overview and ListJava Programming (Core to Spring Boot) · The collections framework
- Arrays and slicesGo Programming (backend and cloud) · Collections and structs
- Collections: List, Dictionary, HashSet, Queue and StackC# and .NET · Collections, generics and LINQ
Questions people ask about this
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
Which interface does NOT extend Collection?Related
Which operation turns List<Order> into Map<String, List<Order>>?Related
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 more topic in “Classes, objects and collections” before its exam: Collection operations.
- Module 3 exam: Classes, objects and collections · 14 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Coroutines and Flow. 50 topics left in the course before the final exam.