Kotlin Sets

A set is a collection that holds unique values only. If you add the same item twice, the set keeps only one copy. Sets do not guarantee a specific order. Use a set when you need to track membership and duplicates must not exist.

Creating a Set

val colors = setOf("red", "blue", "green", "red", "blue")
println(colors)   // [red, blue, green]  — duplicates removed automatically

Set vs List


┌─────────────────────────────────────────────────────┐
│                List           Set                   │
├─────────────────────────────────────────────────────│
│ Allows duplicates    YES            NO              │
│ Maintains order      YES          not guaranteed    │
│ Index access (list[0]) YES         NO               │
│ Fast membership check  slower      faster (hashing) │
│ Use case           ordered data  unique items only  │
└─────────────────────────────────────────────────────┘

Checking Membership

val allowed = setOf("admin", "editor", "viewer")

println("admin" in allowed)       // true
println("guest" in allowed)       // false
println(allowed.contains("editor")) // true

Set Operations

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

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

// Intersection: elements present in both sets
println(setA intersect setB)      // [3, 4, 5]

// Difference: elements in A but NOT in B
println(setA subtract setB)       // [1, 2]
println(setB subtract setA)       // [6, 7]

Diagram: Set Operations


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

       setA only │ both │ setB only
       ──────────┼──────┼──────────
         1, 2    │3,4,5 │  6, 7

union:       1, 2, 3, 4, 5, 6, 7
intersect:         3, 4, 5
subtract A-B:  1, 2

Mutable Set

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

tags.add("jvm")       // adds new tag
tags.add("kotlin")    // already exists — ignored silently
tags.remove("mobile") // removes a tag

println(tags)   // [kotlin, android, jvm]  (order may vary)

Converting Between Types

val numbers = listOf(3, 1, 4, 1, 5, 9, 2, 6, 5, 3)
val unique  = numbers.toSet()      // remove duplicates
val back    = unique.toList()      // back to list

println(numbers)  // [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
println(unique)   // [3, 1, 4, 5, 9, 2, 6]
println(back)     // [3, 1, 4, 5, 9, 2, 6]

LinkedHashSet — Preserving Insertion Order

// setOf() uses LinkedHashSet internally — preserves insertion order
val orderedSet = linkedSetOf("banana", "apple", "cherry")
println(orderedSet)   // [banana, apple, cherry]

// HashSet does NOT preserve order
val unordered = hashSetOf("banana", "apple", "cherry")
println(unordered)    // order not guaranteed

Practical Example: Unique Visitors Counter

fun main() {
    val visitors = mutableSetOf()
    val log = listOf(
        "user_101", "user_205", "user_101", "user_308",
        "user_205", "user_101", "user_410", "user_308"
    )

    for (user in log) {
        val isNew = visitors.add(user)
        if (isNew) println("New visitor: $user")
    }

    println("\nTotal unique visitors: ${visitors.size}")
    println("Visitor IDs: $visitors")
}

Output:

New visitor: user_101
New visitor: user_205
New visitor: user_308
New visitor: user_410

Total unique visitors: 4
Visitor IDs: [user_101, user_205, user_308, user_410]

Leave a Comment

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