I have set of String
val set = HashSet<String>()
set.add("a")
set.add("b")
set.add("c")
I need to convert it to array
val array = arrayOf("a", "b", "c")
There are two ways of converting HashSet to the array:Traverse through the HashSet and add every element to the array. To convert a HashSet into an array in java, we can use the function of toArray().
The toArray() method of Java HashSet is used to form an array of the same elements as that of the HashSet. Basically, it copies all the element from a HashSet to a new array.
Kotlin hashSetOf() Kotlin HashSet is a generic unordered collection of elements and it does not contain duplicate elements. It implements the set interface. hashSetOf() is a function which returns a mutable hashSet, which can be both read and written. The HashSet class store all the elements using hashing mechanism.
Use extension function toTypedArray
as follow
set.toTypedArray()
That function belongs to Kotlin Library
/**
* Returns a *typed* array containing all of the elements of this collection.
*
* Allocates an array of runtime type `T` having its size equal to the size of this collection
* and populates the array with the elements of this collection.
* @sample samples.collections.Collections.Collections.collectionToTypedArray
*/
@Suppress("UNCHECKED_CAST")
public actual inline fun <reified T> Collection<T>.toTypedArray(): Array<T> {
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
val thisCollection = this as java.util.Collection<T>
return thisCollection.toArray(arrayOfNulls<T>(0)) as Array<T>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With