Skip to main content

How to convert a HashSet to an Array in Kotlin

How to convert a HashSet to an Array in Kotlin.

Here's a step-by-step tutorial on how to convert a HashSet to an Array in Kotlin:

Step 1: Create a HashSet

First, let's start by creating a HashSet in Kotlin. A HashSet is an unordered collection of unique elements.

val hashSet = hashSetOf("apple", "banana", "orange")

In this example, we have created a HashSet of strings with the elements "apple", "banana", and "orange".

Step 2: Convert HashSet to Array using the toTypedArray() function

To convert a HashSet to an Array in Kotlin, we can use the toTypedArray() function. This function returns an array containing all elements of the HashSet.

val array = hashSet.toTypedArray()

In this example, we call the toTypedArray() function on the hashSet variable and assign the returned array to the array variable.

Step 3: Access the elements of the Array

Now that we have converted the HashSet to an Array, we can access its elements using index notation.

println(array[0]) // Output: apple
println(array[1]) // Output: banana
println(array[2]) // Output: orange

In this example, we use index notation to access the elements of the array variable and print them to the console.

Step 4: Iterate over the Array

If you want to iterate over the elements of the Array, you can use a loop such as a for loop or a forEach loop.

Here's an example using a for loop:

for (element in array) {
println(element)
}

In this example, we use a for loop to iterate over the elements of the array variable and print each element to the console.

And that's it! You have successfully converted a HashSet to an Array in Kotlin.