1. Overview

The Set and MutableSet collections in Kotlin allow us to store unique elements without a defined order.

In this tutorial, we’ll learn how to perform core operations, membership checks, and transformations using Set and MutableSet in Kotlin.

2. Set

In Kotlin, Set represents an immutable collection of elements that exposes only read-only operations. In this section, we’ll explore how to work with Sets.

2.1. Creation

Let’s start by learning how to create a set of numbers using the setOf() method:

val numbers = setOf(1, 2, 3, 4, 5)

Now, let’s confirm that we’ve got all elements in the numbers set:

assertEquals(5, numbers.size)

The result seems correct. Further, it’s important to note that the setOf() method gives a read-only instance of LinkedHashSet.

2.2. Membership Check

To start with, let’s create the colors set that contains three color values, namely, red, green, and blue:

val colors = setOf("red", "green", "blue")

Now, it’s important to know that the Set interface provides the contains() method to check for the membership of an element efficiently. So, let’s go ahead and verify it for a few sample values:

assertTrue(colors.contains("green"))
assertFalse(colors.contains("yellow"))

It looks like we’ve got the correct results.

2.3. Iteration Through Set

Moving on, let’s learn how to iterate over all the elements of a set. For this purpose, we’ll use the numbers set that contains five integer values:

val numbers = setOf(1, 2, 3, 4, 5)

Next, let’s use a for loop to iterate over the numbers set:

val expectedNumbers = setOf(1, 2, 3, 4, 5)
for (number in numbers) {
    assertTrue(expectedNumbers.contains(number))
}

We can see that the number variable gets one element in each iteration from the numbers set.

Lastly, it’s important to note that the setOf() method gives a read-only instance of LinkedHashSet. So, it guarantees ordering while iterating a set.

2.4. Set Operations

Even though the set data structure is immutable in Kotlin, we can perform the set operations, such as intersection, union, and so on, to produce a new set that contains the resultant set.

Let’s start by defining two immutable sets of numbers, namely, setA and setB:

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

Now, let’s use the intersect() method to perform the intersection operation between setA and setB sets:

val intersection = setA.intersect(setB)
assertEquals(setOf(3), intersection)

We can see that the intersection set contains a single element that’s common to setA and setB.

Similarly, we can use the union() method to perform the union operation between the two sets:

val union = setA.union(setB)
assertEquals(setOf(1, 2, 3, 4, 5), union)

As expected, the union set contains all the elements from setA and setB.

Next, let’s see how we can use the plus() method to add an element to an existing set and produce a new resultant set:

val modifiedSet = setA.plus(6)
assertEquals(setOf(1, 2, 3, 6), modifiedSet)

We can notice that the resultant set contains all elements from setA along with the element that we added.

Lastly, we’ll use the minus() method to remove an element from the existing set:

val removedSet = setA.minus(2)
assertEquals(setOf(1, 3), removedSet)

As expected, the removedSet set contains all elements from setA, except the element we removed.

2.5. equals() and hashCode()

Let’s start by defining two sets, namely, setA and setB that contain numbers:

val setA = setOf(1, 2, 3)
val setB = setOf(3, 2, 1)

We must note that both sets contain the same numbers. However, the order in which we added those numbers is different.

Now, let’s see that both sets are equal and have the same hash code:

assertEquals(setA, setB)
assertEquals(setA.hashCode(), setB.hashCode())

It’s worth noting that because of their immutable nature, both setA and setB can reference the same object in the memory if they contain the same collection of elements. As a result, the hashCode() method gives the same value for both sets.

3. MutableSet

In this section, we’ll learn about the MutableSet interface that allows us to create and modify a collection of elements in a set data structure.

3.1. Creation

Let’s learn how to use the mutableSetOf() method to create a mutable set:

val mutableNumbers = mutableSetOf(1, 2, 3)

We must note that the mutableSetOf() method gives a mutable instance of LinkedHashSet.

Additionally, we can verify that the mutableNumbers set contains three numbers as specified during creation:

assertEquals(3, mutableNumbers.size)

Perfect! It looks correct.

3.2. Membership Check

Further, let’s define the colors set that contains three colors, namely, red, green, and blue:

val colors = setOf("red", "green", "blue")

Now, we can use the contains() method to check the membership of elements in the colors set:

assertTrue(colors.contains("green"))
assertFalse(colors.contains("yellow"))

Great! It’s the same as we learned with the immutable sets.

3.3. Adding Elements

The most interesting property of mutable sets is that we can modify them. So, let’s go ahead and use the add() method to add a new color, “yellow” to the colors set:

val colors = mutableSetOf("red", "green", "blue")
colors.add("yellow")

Further, we can verify that the same set is modified and now contains four elements:

assertEquals(4, colors.size)
assertTrue(colors.contains("yellow"))

3.4. Removing Elements

Similar to adding elements, we can remove an element from a mutable set. So, let’s see how we can use the remove() method to remove an existing color, “green,” from the colors set:

val colors = mutableSetOf("red", "green", "blue")
colors.remove("green")

Additionally, we can verify that the original set is modified and contains only two elements:

assertEquals(2, colors.size)
assertFalse(colors.contains("green"))

Fantastic! We’ve built a good understanding of how to add and remove elements from a mutable set.

4. Conversion

We can use the toSet() method to convert a mutable set to an immutable set. Let’s understand this by defining the mutableColors mutable set and then converting it to immutableColors, an immutable set:

val mutableColors = mutableSetOf("red", "green", "blue")
val immutableColors: Set<String> = mutableColors.toSet()

Further, we can verify that all elements from mutableColors set are present in the immutableColors set:

assertEquals(3, immutableColors.size)
assertTrue(immutableColors.contains("red"))
assertTrue(immutableColors.contains("green"))
assertTrue(immutableColors.contains("blue"))

Similarly, we can use the toMutableSet() method to convert an immutable set into a mutable set.

5. Conclusion

In this article, we learned about Set and Mutableset in Kotlin. Furthermore, we explored the different operations supported by each of them. Lastly, we learned how to convert a mutable set into an immutable set and vice versa.

As always, the code from this article is available over on GitHub.