I have an array of String
val array = arrayOf("a", "b", "c")
I need to convert it to HashSet
val set = HashSet<String>()
Use extension function toHashSet
as follow
array.toHashSet()
That function belongs to Kotlin Library
/**
* Returns a [HashSet] of all elements.
*/
public fun <T> Array<out T>.toHashSet(): HashSet<T> {
return toCollection(HashSet<T>(mapCapacity(size)))
}
Convert Array to Set
import java.util.*
fun main(args: Array<String>) {
val array = arrayOf("a", "b", "c")
val set = HashSet(Arrays.asList(*array))
println("Set: $set")
}
When you run the program, the output will be:
Set: [a, b, c]
Directly use toSet(*array)
or toHashSet(*array)
. These are part of Kotlin's standard library.
The asterisk *
is the spread
operator. It applies all elements in a collection individually, each passed in order to a vararg
method parameter.
val array = arrayOf("data", "foo")
// Multiple spreads ["data", "foo", "bar", "data", "foo"]
val mySet = setOf(*array, "bar", *array)
Passing no parameters setOf()
results in an empty set.
These are all of the specific hash types you can use:
setOf()
hashSetOf()
linkedSetOf()
mutableSetOf()
sortableSetOf()
This is how to define the collection item type explicitly.
setOf<String>()
hashSetOf<MyClass>()