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.
Create a
HashSetinstance:val hashSet = HashSet<String>()Add elements to the
HashSet:hashSet.add("apple")
hashSet.add("banana")
hashSet.add("orange")Convert the
HashSetto aSetusing thetoSet()function:val set: Set<String> = hashSet.toSet()The
toSet()function creates a new immutableSetinstance from the elements of theHashSet.Access the elements in the converted
Set:for (element in set) {
println(element)
}This will print:
apple
banana
orangeYou can now work with the converted
Setjust like any otherSetin 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.