Skip to main content

How to convert a HashSet to a List in Kotlin

How to convert a HashSet to a List in Kotlin.

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

Step 1: Create a HashSet

To start, you need to create a HashSet in Kotlin. This can be done using the HashSet constructor or the hashSetOf function. Here's an example:

val hashSet = HashSet<String>()
hashSet.add("Apple")
hashSet.add("Banana")
hashSet.add("Orange")

In this example, we create a HashSet of strings and add three elements to it.

Step 2: Convert HashSet to List using toList() function

Next, you can use the toList() function to convert the HashSet to a List. The toList() function is available in the Kotlin standard library and returns a new List containing the elements of the HashSet in the same order.

val list = hashSet.toList()

In this example, we convert the hashSet to a List called list.

Step 3: Iterate over the List (optional)

If you want to access the elements of the List, you can iterate over it using a for-loop or other methods. Here's an example:

for (item in list) {
println(item)
}

This code will print each element of the List on a separate line.

Step 4: Convert HashSet to MutableList using toMutableList() function (optional) If you need a mutable List instead of an immutable one, you can use the toMutableList() function instead of toList(). The toMutableList() function returns a MutableList that allows you to modify its elements.

val mutableList = hashSet.toMutableList()

In this example, we convert the hashSet to a MutableList called mutableList.

Step 5: Modify the MutableList (optional)

If you have a mutable List, you can modify its elements using various methods available for MutableList. Here's an example:

mutableList[0] = "Grapes"

In this example, we update the first element of the MutableList to "Grapes".

That's it! You have successfully converted a HashSet to a List in Kotlin.