🗃️ Kotlin – Collections Overview: Lists, Sets & Maps Made Simple
🧲 Introduction – Why Learn Kotlin Collections?
Collections are core to modern programming. Kotlin offers a rich and flexible API for working with groups of data through Lists, Sets, and Maps. These collections come in both read-only (immutable) and mutable forms, giving you full control over how your data is stored, accessed, and modified.
🎯 In this guide, you’ll learn:
- What collections are in Kotlin and why they’re important
- Differences between List, Set, and Map
- Immutable vs Mutable collections
- Basic operations on collections
📦 What Are Kotlin Collections?
A collection is a container that holds multiple elements (values, key-value pairs, or unique entries). Kotlin provides:
- List – ordered collection of elements
- Set – unordered collection of unique elements
- Map – collection of key-value pairs
🔍 Immutable vs Mutable Collections
| Type | Description | Examples |
|---|---|---|
| Immutable | Cannot be changed after creation | listOf(), setOf(), mapOf() |
| Mutable | Can add, remove, or modify elements | mutableListOf(), mutableSetOf(), mutableMapOf() |
📃 Kotlin List – Ordered Collection
val colors = listOf("Red", "Green", "Blue") // Immutable
val fruits = mutableListOf("Apple", "Banana", "Cherry") // Mutable
println(colors[0]) // Red
fruits.add("Mango")
- Allows duplicate values
- Indexed access using
[index]
🔁 Kotlin Set – Unique Elements
val uniqueNums = setOf(1, 2, 2, 3) // Only stores 1, 2, 3
val editableSet = mutableSetOf("A", "B", "C")
editableSet.remove("B")
- No duplicate values allowed
- Ideal for membership checks and uniqueness
🔑 Kotlin Map – Key-Value Pairs
val countryCodes = mapOf("US" to "United States", "IN" to "India")
val editableMap = mutableMapOf("A" to 1, "B" to 2)
editableMap["C"] = 3
- Access values using keys:
countryCodes["US"] - Useful for dictionaries and lookup tables
🔁 Looping Through Collections
🔹 List Loop:
for (item in colors) {
println(item)
}
🔹 Set Loop:
for (item in uniqueNums) {
println(item)
}
🔹 Map Loop:
for ((key, value) in countryCodes) {
println("$key -> $value")
}
📚 Common Collection Functions
| Function | Purpose |
|---|---|
size | Total number of elements |
contains(x) | Checks if value exists |
first(), last() | Access first/last element |
filter {} | Returns elements that match criteria |
map {} | Transforms each element |
sorted() | Returns a sorted version of the collection |
🚫 Common Mistakes
| ❌ Mistake | ✅ Fix |
|---|---|
| Mixing immutable and mutable operations | Choose the correct type for your use case |
Expecting setOf(1, 2, 2) to have duplicates | Sets store only unique elements |
| Using keys that don’t exist in a map | Use getOrDefault() or safe calls |
| Assuming order in sets or maps | Only List guarantees order |
✅ Best Practices for Kotlin Collections
| Tip | Why It Matters |
|---|---|
| Use immutable collections by default | Promotes safer, predictable code |
Use lambdas with filter, map, etc. | Leads to concise and expressive data handling |
Avoid using .get(index) repeatedly | Prefer forEach or destructuring when possible |
Combine collections using +, - | Useful for non-mutating operations |
📌 Summary – Recap & Next Steps
Kotlin collections—List, Set, and Map—offer a modern, expressive way to organize and operate on groups of data. With both mutable and immutable options and a rich API of operations, they’re versatile tools in any Kotlin project.
🔍 Key Takeaways:
- Lists hold ordered, indexed elements (with duplicates)
- Sets hold unique elements (no duplicates)
- Maps hold key-value pairs
- Use immutable collections by default; switch to mutable when needed
⚙️ Practical Use:
Collections are used in API responses, user preferences, form validation, data grouping, and configuration across Android and server-side Kotlin applications.
❓ FAQs – Kotlin Collections
❓ What is the difference between listOf() and mutableListOf()?
✅ listOf() creates a read-only list. mutableListOf() allows you to add, remove, or update elements.
❓ How do I check if a value exists in a collection?
✅ Use in keyword or contains():
if ("Apple" in fruits) { ... }
❓ Can I convert an immutable list to a mutable one?
✅ Yes:
val mutable = immutable.toMutableList()
❓ What if I want a collection without duplicates?
✅ Use setOf() or mutableSetOf() for uniqueness.
❓ Can I sort a collection in Kotlin?
✅ Yes. Use .sorted() or .sort() for mutable collections.
Share Now :
