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