Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert Set (HashSet) to Array in Kotlin?

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")
like image 421
Anisuzzaman Babla Avatar asked Jul 16 '18 19:07

Anisuzzaman Babla


People also ask

How do I convert a HashSet to an array?

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().

Is HashSet an array?

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.

How do you make a HashSet with Kotlin?

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.


1 Answers

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>
}
like image 95
Abner Escócio Avatar answered Sep 19 '22 15:09

Abner Escócio