The map() extension function in Kotlin returns a list containing the results of applying the given transform function to each element in the original set.
The syntax of Set.map() extension function is:
fun <T, R> Set<T>.map(transform: (T) -> R): List<R>
This map() extension function of Set returns a list containing the results of applying the given transform function to each element in the original collection.
Parameter | Optional/Required | Description |
---|---|---|
transform | required | A function that takes an element and returns the transformed result. |
Set.map() returns value of type List
.
Using map() to transform a set of integers by doubling each element.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }
println(doubled)
}
[2, 4, 6, 8, 10]
Using map() to transform a set of strings by getting the length of each string.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val lengths = strings.map { it.length }
println(lengths)
}
[3, 3, 5]
Using map() to transform a set of custom objects by extracting a specific property.
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 names = people.map { it.name }
println(names)
}
[Alice, Bob, Charlie]
In this Kotlin tutorial, we learned about map() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.