1. Introduction
As software developers, we often require converting between different data structures to efficiently manage the data across various scenarios. Kotlin offers multiple methods for seamlessly converting one data structure to another, such as traditional loops and in-built functions.
In this tutorial, we’ll look at different ways to convert between an array and a Set in Kotlin.
2. Convert Array to Set
An array is a data structure for ordered collections of elements, whereas a set guarantees uniqueness by disallowing duplicate elements.
In this section, let’s look at multiple ways to convert an array to a set.
2.1. Using toSet()
We can use the toSet() method on an array to convert it to a set. Let’s look at an example:
val arr = arrayOf(1, 5, 2, 4, 1)
val set = arr.toSet()
assertEquals(setOf(1, 5, 2, 4), set)
The toSet() method internally uses LinkedHashSet, ensuring that the order of elements in the resulting set corresponds to that of the input array. Since a set doesn’t allow duplicate elements, the resultant set may contain fewer elements than the input array.
2.2. Using setOf()
Kotlin provides the setOf() function to create a set from a vararg:
val arr = arrayOf(1, 5, 2, 4, 1)
val set = setOf(*arr)
assertEquals(setOf(1, 5, 2, 4), set)
Here, we invoked the setOf() method by using the spread operator on the array to convert it into a vararg. Additionally, the set preserves the identical element order as the array, supported by LinkedHashSet.
2.3. Using the LinkedHashSet Constructor
We create a new set from an array using the LinkedHashSet constructor:
val arr = arrayOf(1, 5, 2, 4, 1)
val set = LinkedHashSet(arr.toList())
assertEquals(setOf(1, 5, 2, 4), set)
In this implementation, we converted an array to a list and then used the LinkedHashSet constructor to create an instance. However, we should note that this implementation is less performant than the other implementations due to multiple conversions.
Instead of LinkedHashSet, we can also use HashSet if we don’t care about preserving the insertion order.
2.4. Using a Loop
Another approach to convert an array to a set is by using a loop. We can use a simple for loop to iterate over the elements of an array and add the elements to the set:
val arr = arrayOf(1, 5, 2, 4, 1)
val mutableSet = mutableSetOf<Int>()
for (i in arr) {
mutableSet.add(i)
}
assertEquals(setOf(1, 5, 2, 4), mutableSet)
Because we’re adding elements within a loop, we opted for a mutable set.
While there are direct methods available, this approach enables the transformation of elements before adding them to the set, which could be useful in certain scenarios.
3. Convert Set to Array
In this section, we’ll look at various ways to convert a set to an array.
3.1. Using toTypedArray()
We can use the method toTypedArray() on a Set to convert it into an array. Let’s look at a sample code:
val set = setOf(1, 2, 3, 4)
val arr = set.toTypedArray()
Assertions.assertArrayEquals(arrayOf(1, 2, 3, 4), arr)
Kotlin automatically assigns the type of the array based on the type of the Set. This is particularly useful when we need to work with arrays instead of collections, providing a convenient way to convert between the two data structures.
3.2. Using Array Constructor
Another way to convert a Set to an array is by using the Array() constructor along with the elementAt() method on the Set:
val set = setOf(1, 2, 3, 4)
val arr = Array(set.size) { set.elementAt(it) }
Assertions.assertArrayEquals(arrayOf(1, 2, 3, 4), arr)
In this scenario, we’re creating an array with the same size as the set. Then, we use a lambda function to initialize each element of the array from the corresponding element from the Set.
3.3. Using a Loop
We can also use a loop to iterate through the elements of the set and add them to an array:
val set = setOf(1, 2, 3, 4)
val arr = arrayOfNulls<Int>(set.size)
var index = 0
for (element in set) {
arr[index++] = element
}
Assertions.assertArrayEquals(arrayOf(1, 2, 3, 4), arr)
First, we create an array with the same size as the set, initializing it with null values. Then, we iterate through each element of the set and add it to the corresponding position in the array.
We can also use a not-null array and initialize it with a default value:
val arr = Array(set.size) { 0 }
Using this approach, we can eliminate the need for null values, although this may incur a minor performance overhead, especially with larger arrays.
4. Conclusion
In this article, we discussed different ways to convert an array to a set and vice-versa. Moreover, we examined direct conversion methods alongside loop-based approaches. Consequently, depending on the scenario, we can opt for the most suitable approach.
As always, the sample code used here is available over on GitHub.