Kotlin Set toHashSet()
Syntax & Examples
toHashSet() extension function
The toHashSet() extension function in Kotlin returns a new HashSet containing all the elements of the collection.
Syntax of toHashSet()
The syntax of Set.toHashSet() extension function is:
fun <T> Set<T>.toHashSet(): HashSet<T>
This toHashSet() extension function of Set returns a new HashSet of all elements.
Return Type
Set.toHashSet() returns value of type HashSet
.
✐ Examples
1 Converting a set of integers to a HashSet
Using toHashSet() to convert a set of integers to a HashSet.
For example,
- Create a set of integers.
- Use toHashSet() to convert the set to a HashSet.
- Print the resulting HashSet.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val hashSet = numbers.toHashSet()
println(hashSet)
}
Output
[1, 2, 3, 4, 5]
2 Converting a set of strings to a HashSet
Using toHashSet() to convert a set of strings to a HashSet.
For example,
- Create a set of strings.
- Use toHashSet() to convert the set to a HashSet.
- Print the resulting HashSet.
Kotlin Program
fun main() {
val strings = setOf("one", "two", "three")
val hashSet = strings.toHashSet()
println(hashSet)
}
Output
[one, two, three]
3 Converting a set of custom objects to a HashSet
Using toHashSet() to convert a set of custom objects to a HashSet.
For example,
- Create a data class.
- Create a set of custom objects.
- Use toHashSet() to convert the set to a HashSet.
- Print the resulting HashSet.
Kotlin Program
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val hashSet = people.toHashSet()
println(hashSet)
}
Output
[Person(name=Alice, age=30), Person(name=Bob, age=25), Person(name=Charlie, age=35)]
Summary
In this Kotlin tutorial, we learned about toHashSet() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.