Skip to main content

How to convert a set to an array in Kotlin

How to convert a set to an array in Kotlin.

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

Step 1: Create a set

First, you need to create a set in Kotlin. A set is a collection of unique elements. You can create a set using the setOf() function.

val set = setOf("apple", "banana", "orange")

In this example, we have created a set of fruits.

Step 2: Convert set to array using the toTypedArray() function

To convert the set to an array, you can use the toTypedArray() function. This function is available on the set and it returns an array containing all the elements of the set.

val array = set.toTypedArray()

In this example, we convert the set of fruits to an array.

Step 3: Access the elements of the array

You can access the elements of the array using the index. The index starts from 0, so the first element can be accessed using array[0], the second element using array[1], and so on.

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

In this example, we print the elements of the array.

Step 4: Iterate over the array

If you want to iterate over the elements of the array, you can use a loop. Kotlin provides several loop constructs, such as for and forEach.

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

array.forEach { element ->
println(element)
}

In these examples, we iterate over the array and print each element.

Step 5: Convert array to mutable array

If you need to modify the array, you can convert it to a mutable array using the toMutableList() function. This function returns a mutable list, which can be converted back to an array using the toTypedArray() function.

val mutableArray = array.toMutableList().toTypedArray()

In this example, we convert the array to a mutable array.

That's it! You have successfully converted a set to an array in Kotlin.