Kotlin Sets — Complete Guide

1. What is a Set in Kotlin?

A Set in Kotlin is a collection that contains unique elements — duplicates are automatically removed. Use sets when you want to avoid storing duplicates or when order doesn’t matter.

Example:

// Example: Set of fruits
val fruits = setOf("Apple", "Banana", "Cherry", "Apple")
println(fruits) // [Apple, Banana, Cherry] — duplicates removed
            

2. How to Declare and Use Sets (with Examples)

Example 1 — Using setOf() (Immutable Set)

// Basic declaration
val colors = setOf("Red", "Green", "Blue", "Red")
println(colors) // [Red, Green, Blue]
println("Red" in colors) // true
        
Example 2 — Using mutableSetOf() (Mutable Set)

// Create a mutable set
val cities = mutableSetOf("Lahore", "Karachi", "Islamabad")

// Add or remove elements
cities.add("Quetta")
cities.add("Karachi") // duplicate ignored
cities.remove("Lahore")

println(cities) // [Karachi, Islamabad, Quetta]
        
Example 3 — Using LinkedHashSet to Preserve Order

val linked = linkedSetOf("A", "B", "C", "A")
println(linked) // [A, B, C] — maintains insertion order
        
Example 4 — Using HashSet

val hashSet = hashSetOf(10, 5, 20, 5)
println(hashSet) // [10, 5, 20] — order not guaranteed
        
Example 5 — Traversing, Filtering, and Mapping a Set

// Traversing
val fruitsSet = setOf("Apple", "Banana", "Cherry")
fruitsSet.forEach { println(it) }

// Filtering
val aFruits = fruitsSet.filter { it.startsWith("A") }
println(aFruits) // [Apple]

// Mapping / Transforming
val lengths = fruitsSet.map { it.length }
println(lengths) // [5, 6, 6]

// Chaining
val result = fruitsSet.filter { it.contains("a", ignoreCase = true) }
                      .map { it.uppercase() }
println(result) // [APPLE, BANANA, CHERRY]

// Convert back to Set if needed
val uniqueResult = result.toSet()
println(uniqueResult)
        
Example 6 — Common Set Operations

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

// Union (combine)
println(setA union setB) // [1, 2, 3, 4, 5, 6]

// Intersection (common)
println(setA intersect setB) // [3, 4]

// Difference
println(setA subtract setB) // [1, 2]
        

3. When and When Not to Use Sets?

✅ When to Use Sets:
🚫 When Not to Use Sets:

4. Top 8 Interview Questions (With Answers)

  1. Q1: What is the main difference between List and Set?
    Ans: List allows duplicates and maintains order. Set contains unique elements only.
  2. Q2: Can a Set contain duplicate elements?
    Ans: No. Duplicates are automatically removed.
  3. Q3: How do you create a mutable set in Kotlin?
    Ans: Use mutableSetOf().
    
    val set = mutableSetOf(1, 2, 3)
    set.add(4)
                    
  4. Q4: Does Kotlin’s Set maintain order?
    Ans: HashSet does not, but LinkedHashSet preserves insertion order.
  5. Q5: How do you find common elements between two sets?
    Ans: Use intersect().
    
    val result = setA intersect setB
                    
  6. Q6: How do you combine two sets in Kotlin?
    Ans: Use union().
  7. Q7: How do you check if an element exists in a Set?
    Ans: Use the in keyword or contains() method.
    
    if ("Ali" in namesSet) println("Found!")
                    
  8. Q8: How do you remove duplicates from a List using a Set?
    Ans:
    
    val nums = listOf(1, 2, 2, 3)
    val unique = nums.toSet()
    println(unique) // [1, 2, 3]
                    
Bonus Tip 💡

In Android development, Set is great for storing unique user IDs, permissions, or tags where duplication should be avoided.


val userPermissions = mutableSetOf("READ", "WRITE")
userPermissions.add("READ") // ignored automatically
println(userPermissions) // [READ, WRITE]