Convert a List to a Set in Kotlin
This article explores different ways to convert a list to a set in Kotlin. Assume that the list contains all distinct elements; otherwise, all duplicate values would be silently discarded.
1. Using Copy Constructor
The HashSet constructor can take another collection and construct a new Set containing those collection elements. The standard name for this type of constructor is the copy constructor.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun <T> convertToSet(list: List<T>): Set<T> { return HashSet(list) } fun main() { val ints: List<Int> = listOf(1, 2, 3, 4, 5) val set: Set<Int> = convertToSet(ints) println(set) // [1, 2, 3, 4, 5] } |
2. Using toSet() function
Another preferable approach to convert the specified list to a set in Kotlin is using toSet() or toMutableSet() function.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun <T> convertToSet(list: List<T>): Set<T> { return list.toSet() } fun main() { val ints: List<Int> = listOf(1, 2, 3, 4, 5) val set: Set<Int> = convertToSet(ints) println(set) // [1, 2, 3, 4, 5] } |
3. Custom Routine
You can also write your own custom logic for this task. The idea is to create an empty Set and add every element of the specified list to it.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun <T> convertToSet(list: List<T>): Set<T> { val set: MutableSet<T> = HashSet() for (e in list) { set.add(e) } return set } fun main() { val ints: List<Int> = listOf(1, 2, 3, 4, 5) val set: Set<Int> = convertToSet(ints) println(set) // [1, 2, 3, 4, 5] } |
That’s all about converting a list 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 :)