Convert an array to a set in Kotlin
Set has unique values, so to create an a Set from an Array we can useHashSet()
function which returns a Set and take array list as parameter. In below example we will pass array with values: "a", "b", "c", "a" we should expect the output of set is: "a", "b", "c"import java.util.*
fun main(args: Array<String>) {
val array = arrayOf("a", "b", "c", "a")
val set = HashSet(Arrays.asList(*array))
println("Set: $set")
}
Output
Set: [a, b, c]
Set in Kotlin is case sensitive
In below example we will pass array with values: "a", "b", "c", "A" we should expect the output of set is: "a", "A", "b", "c"import java.util.*
fun main(args: Array<String>) {
val array = arrayOf("a", "b", "c", "A")
val set = HashSet(Arrays.asList(*array))
println("Set: $set")
}
Output
Set: [a, A, b, c]