Convert an array to a set in Kotlin
This article explores different ways to convert an array to a set using Kotlin. Assume that the array contains all distinct elements; otherwise, all duplicates would be silently discarded.
1. Using toSet() function
In Kotlin, the standard way to convert the specified array to a set is with the toSet() or toMutableSet() function.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun <T> convertToSet(array: Array<T>): Set<T> { return array.toSet() } fun main() { val array = arrayOf("A", "B", "C", "D", "E") val set = convertToSet(array) println(set) // [A, B, C, D, E] } |
2. Using setOf() function
Another plausible way is to pass the expanded array returned by the Spread operator to the setOf() or mutableSetOf function.
|
1 2 3 4 5 6 7 |
fun main() { val array = arrayOf("A", "B", "C", "D", "E") val set = setOf(*array) println(set) // [A, B, C, D, E] } |
3. Using for loop
Finally, you can write your own custom logic for this task. The idea is to create an empty set and push every element of the specified array to it using a for-loop.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun <T> convertToSet(array: Array<T>): Set<T> { val set: MutableSet<T> = HashSet() for (i in array) { set.add(i) } return set } fun main() { val array = arrayOf("A", "B", "C", "D", "E") val set = convertToSet(array) println(set) // [A, B, C, D, E] } |
That’s all about converting an array to a set in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)