In this article, we will explore Sets in Kotlin. A Set is a collection that contains no duplicate elements and is generally used to store unique items. Kotlin provides a set of built-in methods and features to efficiently work with Sets.
Creating a Set
Kotlin provides two types of sets: mutable and immutable. The Set interface represents an immutable set, while MutableSet represents a mutable set. Let’s start by creating an immutable set.
val immutableSet = setOf(1, 2, 3, 4, 5)
If you print this set, you will see the output:
println(immutableSet) // Output: [1, 2, 3, 4, 5]
Next, let’s create a mutable set:
val mutableSet = mutableSetOf(1, 2, 3)
Adding and Removing Elements
With MutableSet, you can add and remove elements.
mutableSet.add(4)
mutableSet.remove(1)
println(mutableSet) // Output: [2, 3, 4]
Unique Characteristics of Sets
One of the main characteristics of sets is that they do not allow duplicate values. Let’s examine this with an example:
val duplicateSet = setOf(1, 1, 2, 2, 3, 3)
println(duplicateSet) // Output: [1, 2, 3]
As you can see, duplicates are automatically removed upon the creation of the set.
Set Operations
Kotlin provides several standard operations on sets:
union: Returns a set containing all elements that are either in one of the sets or both.intersect: Returns a set containing elements that are only in both sets.subtract: Returns a set containing elements that are in the first set but not in the second.
val setA = setOf(1, 2, 3)
val setB = setOf(3, 4, 5)
println(setA.union(setB)) // Output: [1, 2, 3, 4, 5]
println(setA.intersect(setB)) // Output: [3]
println(setA.subtract(setB)) // Output: [1, 2]
Iterating Over a Set
Iterating over a set can be done in several ways. The most common way is to use a simple for-loop:
for (item in immutableSet) {
println(item)
}
You can also utilize the forEach higher-order function:
immutableSet.forEach { item ->
println(item)
}
Conclusion
Sets in Kotlin are a great way to manage collections of unique items. Whether you need mutable or immutable sets, Kotlin offers flexibility and powerful functionality to handle set operations easily. Try using sets in your Kotlin projects and enjoy the benefits of their unique characteristics!