Sets in Kotlin
📌 Sets in Kotlin
In Kotlin, a Set is a collection of unique elements. Unlike lists, sets do not allow duplicate values and are useful when you need to maintain a collection of distinct objects.
Kotlin provides two types of sets:
Immutable Set (
Set) → Read-only, cannot be modified.Mutable Set (
MutableSet) → Allows adding, removing, and updating elements.
✅ Creating Sets in Kotlin
📌 1. Immutable Set
Use
setOf()to create a read-only set.
fruits = setOf("Apple", "Banana", "Orange", "Apple")println(fruits) // Output: [Apple, Banana, Orange]
Duplicates are removed automatically.
📌 2. Mutable Set
Use
mutableSetOf()to create a modifiable set.
val numbers = mutableSetOf(1, 2, 3, 4)numbers.add(5) // Add elementnumbers.remove(2) // Remove elementprintln(numbers) // Output: [1, 3, 4, 5]
✅ Set Functions in Kotlin
| Function | Description | Example |
|---|---|---|
add() | Adds an element to the set | set.add(10) |
remove() | Removes an element from the set | set.remove(5) |
contains() | Checks if an element is present | set.contains(3) |
isEmpty() | Checks if the set is empty | set.isEmpty() |
size | Returns the number of elements in the set | set.size |
clear() | Removes all elements from the set | set.clear() |
✅ Iterating Over a Set
You can iterate over a set using different approaches.
📌 1. Using For Loop
val items = setOf("Pen", "Book", "Laptop")for (item in items) { println(item)}
📌 2. Using forEach()
items.forEach { println(it) }
✅ Set Operations in Kotlin
Kotlin supports standard set operations like Union, Intersection, and Difference.
| Operation | Description | Example | Output |
|---|---|---|---|
union() | Combines two sets, removing duplicates | set1.union(set2) | Merged Set |
intersect() | Returns common elements between sets | set1.intersect(set2) | Common Elements |
subtract() | Returns elements from set1 not in set2 | set1.subtract(set2) | Difference |
📌 Example:
val set1 = setOf(1, 2, 3, 4)val set2 = setOf(3, 4, 5, 6)println("Union: ${set1.union(set2)}") println("Intersection: ${set1.intersect(set2)}") println("Subtract: ${set1.subtract(set2)}") // [1, 2]
✅ Set vs List in Kotlin
| Feature | Set | List |
|---|---|---|
| Duplicates | No duplicates allowed | Allows duplicates |
| Order | Unordered (No guaranteed order) | Ordered (Elements have an index) |
| Access by Index | Not possible | Possible using index (list[0]) |
| Performance for Search | Faster for search (HashSet implementation) | Slower for large datasets |
✅ Conclusion
Use Sets when you need to store unique elements without duplicates.
Immutable Sets are useful for read-only data, while Mutable Sets are great for dynamic data.
Perform operations like union, intersection, and difference easily.