Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Sets in Kotlin

Introduction to Sets

A set is a collection of unique elements. In Kotlin, sets are part of the Collections framework and can be used to store groups of objects. Sets do not allow duplicate values, which makes them useful for scenarios where you want to ensure that each element is distinct.

Creating Sets

In Kotlin, you can create a set using the setOf() function. This function creates a read-only set. If you need a mutable set, you can use mutableSetOf().

Example: Creating a Set

val readOnlySet = setOf(1, 2, 3, 4)
Output: [1, 2, 3, 4]
val mutableSet = mutableSetOf(1, 2, 3, 4)
Output: [1, 2, 3, 4]

Adding and Removing Elements

To add elements to a mutable set, use the add() method. To remove elements, use the remove() method.

Example: Adding and Removing Elements

mutableSet.add(5)
Output: [1, 2, 3, 4, 5]
mutableSet.remove(2)
Output: [1, 3, 4, 5]

Set Operations

Kotlin provides several operations that can be performed on sets, such as union, intersection, and difference.

Example: Set Operations

val setA = setOf(1, 2, 3)
val setB = setOf(3, 4, 5)
val unionSet = setA union setB
Output: [1, 2, 3, 4, 5]
val intersectionSet = setA intersect setB
Output: [3]
val differenceSet = setA subtract setB
Output: [1, 2]

Iterating Over Sets

You can iterate over the elements of a set using a for loop. Since sets are unordered collections, the order of the elements may vary.

Example: Iterating Over a Set

for (number in mutableSet) {
println(number)
}
Output:
1
                    3
                    4
                    5

Conclusion

Sets in Kotlin provide a powerful way to manage collections of unique elements. With various operations and methods available, you can easily manipulate and interact with sets in your programs. Whether you need a fixed collection of unique items or a mutable collection, Kotlin's set functionality has you covered.