The mapTo() extension function in Kotlin applies the given transform function to each element of the original set, and appends the results to the given destination.
The syntax of Set.mapTo() extension function is:
fun <T, R, C : MutableCollection<in R>> Set<T>.mapTo(destination: C, transform: (T) -> R): C
This mapTo() extension function of Set applies the given transform function to each element of the original collection and appends the results to the given destination.
Parameter | Optional/Required | Description |
---|---|---|
destination | required | The collection to which the results will be appended. |
transform | required | A function that takes an element and returns the transformed result. |
Set.mapTo() returns value of type C
.
Using mapTo() to transform a set of integers by doubling each element, and appending them to a list.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val destination = mutableListOf<Int>()
numbers.mapTo(destination) { it * 2 }
println(destination)
}
[2, 4, 6, 8, 10]
Using mapTo() to transform a set of strings by getting the length of each string, and appending them to a list.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val destination = mutableListOf<Int>()
strings.mapTo(destination) { it.length }
println(destination)
}
[3, 3, 5]
Using mapTo() to transform a set of custom objects by extracting a specific property, and appending them to a list.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val destination = mutableListOf<String>()
people.mapTo(destination) { it.name }
println(destination)
}
[Alice, Bob, Charlie]
In this Kotlin tutorial, we learned about mapTo() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.