Kotlin Maps and Sets

Maps and sets are two more ways to store collections of data. Each solves a different problem — maps connect keys to values like a dictionary, while sets store unique values with no duplicates.

Maps — Key-Value Storage

A map stores data in pairs: a unique key linked to a value. Think of a real dictionary — each word (key) has a definition (value). Looking up a word gives you its definition instantly.

Immutable Map

val capitals = mapOf(
    "India"  to "New Delhi",
    "France" to "Paris",
    "Japan"  to "Tokyo"
)

println(capitals["India"])        // New Delhi
println(capitals.get("France"))   // Paris
println(capitals.size)            // 3
println(capitals.containsKey("Japan"))   // true
println(capitals.containsValue("Rome"))  // false

Diagram — Map Structure

Key          Value
──────────── ──────────
"India"   →  "New Delhi"
"France"  →  "Paris"
"Japan"   →  "Tokyo"

capitals["India"] looks up the key and returns the value.

Mutable Map

val phonebook = mutableMapOf(
    "Alice" to "9876543210",
    "Bob"   to "9123456789"
)

phonebook["Carol"] = "9000011111"     // Add new entry
phonebook["Alice"] = "9999999999"     // Update existing entry
phonebook.remove("Bob")               // Remove by key

println(phonebook)
// {Alice=9999999999, Carol=9000011111}

Iterating Over a Map

val scores = mapOf("Riya" to 95, "Arun" to 87, "Neha" to 91)

for ((name, score) in scores) {
    println("$name scored $score")
}

// Using keys and values separately
for (name in scores.keys) { println(name) }
for (score in scores.values) { println(score) }

Useful Map Functions

val inventory = mapOf("Apples" to 50, "Mangoes" to 30, "Bananas" to 0)

// Get value or use a default if key not found
println(inventory.getOrDefault("Grapes", 0))   // 0

// Filter entries
val inStock = inventory.filter { it.value > 0 }
println(inStock)   // {Apples=50, Mangoes=30}

// Transform values
val doubled = inventory.mapValues { it.value * 2 }
println(doubled)   // {Apples=100, Mangoes=60, Bananas=0}

Sets — Collections of Unique Values

A set automatically rejects duplicate values. If you add the same value twice, the set keeps only one copy. Sets also do not maintain order — the items can appear in any sequence.

Immutable Set

val colors = setOf("Red", "Green", "Blue", "Red", "Green")
println(colors)       // [Red, Green, Blue] — duplicates removed
println(colors.size)  // 3
println("Blue" in colors)   // true

Mutable Set

val tags = mutableSetOf("kotlin", "android", "mobile")

tags.add("jetpack")       // Added
tags.add("kotlin")        // Ignored — already exists
tags.remove("mobile")

println(tags)   // [kotlin, android, jetpack]

Diagram — Set vs List With Duplicates

Input values: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]

As a List:   [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]  ← keeps duplicates
             size = 10

As a Set:    [1, 2, 3, 4, 5, 6, 9]            ← duplicates removed
             size = 7

Set Operations

val setA = setOf(1, 2, 3, 4, 5)
val setB = setOf(4, 5, 6, 7, 8)

// Union — all elements from both sets
println(setA union setB)         // [1, 2, 3, 4, 5, 6, 7, 8]

// Intersection — only elements in BOTH sets
println(setA intersect setB)     // [4, 5]

// Difference — elements in setA but NOT in setB
println(setA subtract setB)      // [1, 2, 3]

Diagram — Set Operations Visualized

setA = {1,2,3,4,5}    setB = {4,5,6,7,8}

Union:                Intersection:     Difference(A-B):
{1,2,3,4,5,6,7,8}    {4,5}             {1,2,3}

 A   ∩   B             A ∩ B              A only
┌───────────────┐     ┌───┐             ┌─────┐
│1 2 3│4 5│6 7 8│     │4 5│             │1 2 3│
└───────────────┘     └───┘             └─────┘

Choosing the Right Collection

Need                             | Use
---------------------------------|-------------
Ordered list, duplicates OK      | List / Array
Key-value lookup                 | Map
No duplicates, fast membership   | Set
Change size dynamically          | Mutable version
Read-only data                   | Immutable version

Leave a Comment

Your email address will not be published. Required fields are marked *