🧩 Kotlin – Sets (Mutable & Immutable): Unique Collection Explained
🧲 Introduction – Why Learn Kotlin Sets?
Sets are unordered collections of unique elements, ideal for ensuring that no duplicate data exists. Kotlin makes working with sets intuitive by offering both immutable and mutable variants. Sets are perfect for scenarios like tags, filters, unique IDs, and rule-based checks.
🎯 In this guide, you’ll learn:
- What Sets are in Kotlin and when to use them
- Difference between immutable and mutable sets
- How to add, remove, and check items in a set
- Best practices for handling uniqueness in collections
🧮 What Is a Set in Kotlin?
A Set is a collection that:
- Holds unique elements (no duplicates)
- Does not guarantee order
- Supports both read-only (
setOf
) and modifiable (mutableSetOf
) types
🛡️ Immutable Sets – setOf()
An immutable set cannot be changed after creation.
val languages = setOf("Kotlin", "Java", "Python", "Kotlin")
println(languages) // [Kotlin, Java, Python]
✔️ Only unique values are retained (duplicate "Kotlin"
is removed).
🛠️ Mutable Sets – mutableSetOf()
Mutable sets allow adding, removing, and modifying elements.
val tools = mutableSetOf("Git", "Docker", "Kubernetes")
tools.add("Gradle")
tools.remove("Docker")
println(tools) // [Git, Kubernetes, Gradle]
🔁 Iterating Over Sets
🔹 Using for
loop:
for (tool in tools) {
println("Tool: $tool")
}
🔹 Using forEach
lambda:
languages.forEach { println("Lang: $it") }
🔍 Set Functions & Operations
Function | Description |
---|---|
contains(x) | Checks if element exists |
add(x) | Adds element (only in mutable sets) |
remove(x) | Removes element |
union(set) | Combines two sets |
intersect(set) | Returns common elements |
subtract(set) | Removes all elements from another set |
isEmpty() | Checks if the set has no elements |
🔹 Example:
val setA = setOf(1, 2, 3)
val setB = setOf(3, 4, 5)
println(setA union setB) // [1, 2, 3, 4, 5]
println(setA intersect setB) // [3]
println(setA subtract setB) // [1, 2]
🔃 Convert Between Mutable and Immutable Sets
val immutable = setOf("X", "Y")
val mutable = immutable.toMutableSet()
mutable.add("Z")
val backToImmutable = mutable.toSet()
🧬 HashSet and LinkedHashSet in Kotlin
Type | Description |
---|---|
HashSet | Unordered, fast lookup |
LinkedHashSet | Maintains insertion order |
val orderedSet = linkedSetOf("A", "B", "C")
println(orderedSet) // [A, B, C]
✅ Best Practices for Kotlin Sets
Tip | Why It Matters |
---|---|
Use setOf() for fixed reference | Promotes immutability and thread safety |
Use mutableSetOf() for flexibility | Enables add/remove operations |
Use union() , intersect() | Cleaner than manually iterating for comparisons |
Avoid duplicate checks manually | Let Set handle it automatically |
🚫 Common Mistakes with Sets
❌ Mistake | ✅ Fix |
---|---|
Expecting duplicates in setOf() | Sets store only unique values |
Modifying immutable set | Use mutableSetOf() or convert with toMutableSet() |
Relying on order | Use List or LinkedHashSet if order is important |
Confusing Set with Map | Set stores only values, not key-value pairs |
📌 Summary – Recap & Next Steps
Kotlin Sets are perfect for ensuring uniqueness and performing set-based operations like union and intersection. With both immutable and mutable options, they suit a wide range of real-world applications.
🔍 Key Takeaways:
- Sets store unique, unordered elements
- Use
setOf()
for immutable,mutableSetOf()
for editable sets - Built-in operations like
union()
,intersect()
simplify logic - Use
LinkedHashSet
to maintain insertion order
⚙️ Practical Use:
Sets are widely used in permission management, form validation, tag lists, and deduplication tasks in both Android and server-side Kotlin apps.
❓ FAQs – Kotlin Sets
❓ Can Kotlin Sets contain duplicate elements?
✅ No. All elements in a set are unique. Duplicate entries are automatically removed.
❓ What is the difference between setOf()
and mutableSetOf()
?
✅ setOf()
is read-only and cannot be modified. mutableSetOf()
allows add/remove operations.
❓ How do I ensure my Set maintains insertion order?
✅ Use linkedSetOf()
or LinkedHashSet
.
❓ Can I convert a list to a set?
✅ Yes. Use .toSet()
:
val names = listOf("A", "B", "A")
val uniqueNames = names.toSet() // ["A", "B"]
❓ Is a Set faster than a List in Kotlin?
✅ Sets offer faster lookup performance, especially for contains()
operations, due to internal hashing.
Share Now :