Kotlin Collections — Complete Guide

1. What Are Collections in Kotlin?

In Kotlin, a Collection is a data structure that holds multiple elements. Collections help you store, organize, and manipulate groups of related data efficiently.

Kotlin collections are categorized into three main types: Lists, Sets, and Maps. Collections can also be either read-only (immutable) or mutable.

2. Collection Hierarchy in Kotlin


3. Types of Collections

1️⃣ Lists

A List is an ordered collection. Duplicates are allowed. Kotlin provides:


// Immutable List
val fruits = listOf("Apple", "Banana", "Cherry")

// Mutable List
val numbers = mutableListOf(1, 2, 3)
numbers.add(4)
        
2️⃣ Sets

A Set stores unique elements. Duplicates are automatically removed.


val uniqueNumbers = setOf(1, 2, 2, 3) // [1, 2, 3]
val mutableSet = mutableSetOf("A", "B")
mutableSet.add("C")
        
3️⃣ Maps

A Map stores key-value pairs. Keys are unique, values can repeat. Kotlin provides:


// Immutable Map
val capitals = mapOf("Pakistan" to "Islamabad", "USA" to "Washington")

// Mutable Map
val mutableCapitals = mutableMapOf("India" to "New Delhi")
mutableCapitals["UK"] = "London"
        

4. Functional Operations on Collections

Kotlin collections provide powerful higher-order functions for traversing, filtering, mapping, and more.


// Example: List operations
val numbers = listOf(1, 2, 3, 4, 5)

// Filter even numbers
val evenNumbers = numbers.filter { it % 2 == 0 }

// Map to double
val doubled = numbers.map { it * 2 }

// Find first number > 3
val firstLarge = numbers.find { it > 3 }

println(evenNumbers) // [2, 4]
println(doubled)     // [2, 4, 6, 8, 10]
println(firstLarge)  // 4
        

5. Traversing Collections


// Using for loop
for (num in numbers) println(num)

// Using forEach
numbers.forEach { println(it) }

// Traversing Sets
val namesSet = setOf("Ali", "Ahmed", "Zain")
namesSet.forEach { println(it) }

// Traversing Maps
val capitalsMap = mapOf("Pakistan" to "Islamabad", "USA" to "Washington")
capitalsMap.forEach { (country, capital) ->
    println("$country -> $capital")
}
        

6. Key Differences Between Collection Types

Feature List Set Map
DuplicatesAllowedNot allowedKeys unique, values can repeat
OrderMaintainedNot guaranteed (LinkedHashSet preserves)Not guaranteed (LinkedHashMap preserves)
Index AccessYesNoNo
Mutable / ImmutableList / MutableListSet / MutableSetMap / MutableMap
Functional Operationsfilter, map, find, sorted...filter, map, find...mapKeys, mapValues, filterKeys...

7. When to Use Which Collection?

Bonus Tip 💡

Use immutable collections whenever possible for safer, predictable code. Use mutable collections when you need to modify data dynamically.