Kotlin List toMutableSet()
Syntax & Examples
Syntax of List.toMutableSet()
The syntax of List.toMutableSet() extension function is:
fun <T> Iterable<T>.toMutableSet(): MutableSet<T>
This toMutableSet() extension function of List returns a new MutableSet containing all distinct elements from the given collection.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing integers1, 2, 2, 3, 4, 4, 5
. - We convert
list1
to a MutableSet using thetoMutableSet()
extension function. - We print the
mutableSet
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 2, 3, 4, 4, 5)
val mutableSet = list1.toMutableSet()
println(mutableSet)
}
Output
[1, 2, 3, 4, 5]
2 Example
In this example,
- We create a list named
list2
containing characters'a', 'b', 'c', 'c', 'd'
. - We convert
list2
to a MutableSet using thetoMutableSet()
extension function. - We print the
mutableSet
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf('a', 'b', 'c', 'c', 'd')
val mutableSet = list2.toMutableSet()
println(mutableSet)
}
Output
[a, b, c, d]
3 Example
In this example,
- We create a list named
list3
containing strings"apple", "banana", "apple", "cherry"
. - We convert
list3
to a MutableSet using thetoMutableSet()
extension function. - We print the
mutableSet
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf("apple", "banana", "apple", "cherry")
val mutableSet = list3.toMutableSet()
println(mutableSet)
}
Output
[apple, banana, cherry]
Summary
In this Kotlin tutorial, we learned about toMutableSet() extension function of List: the syntax and few working examples with output and detailed explanation for each example.