Skip to main content

How to convert a HashSet to a Set in Kotlin

How to convert a HashSet to a Set in Kotlin.

Here's a step-by-step tutorial on how to convert a HashSet to a Set in Kotlin.

  1. Create a HashSet instance:

    val hashSet = HashSet<String>()
  2. Add elements to the HashSet:

    hashSet.add("apple")
    hashSet.add("banana")
    hashSet.add("orange")
  3. Convert the HashSet to a Set using the toSet() function:

    val set: Set<String> = hashSet.toSet()

    The toSet() function creates a new immutable Set instance from the elements of the HashSet.

  4. Access the elements in the converted Set:

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

    This will print:

    apple
    banana
    orange

    You can now work with the converted Set just like any other Set in Kotlin.

Alternatively, you can directly convert a HashSet to a Set using the HashSet constructor when creating the Set:

val set: Set<String> = HashSet(hashSet)

This approach is useful when you need to perform conversions in a single line of code.

Remember that the converted Set will be immutable. If you need a mutable Set, you can use the toMutableSet() function instead of toSet().

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