Kotlin Tutorials

Kotlin Set map()
Syntax & Examples

Set.map() extension function

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.


Syntax of Set.map()

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.

Parameters

ParameterOptional/RequiredDescription
transformrequiredA function that takes an element and returns the transformed result.

Return Type

Set.map() returns value of type List.



✐ Examples

1 Transforming a set of integers by doubling each element

Using map() to transform a set of integers by doubling each element.

For example,

  1. Create a set of integers.
  2. Use map() with a transform function that doubles each element.
  3. Print the resulting list.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val doubled = numbers.map { it * 2 }
    println(doubled)
}

Output

[2, 4, 6, 8, 10]

2 Transforming a set of strings by getting their lengths

Using map() to transform a set of strings by getting the length of each string.

For example,

  1. Create a set of strings.
  2. Use map() with a transform function that returns the length of each string.
  3. Print the resulting list.

Kotlin Program

fun main() {
    val strings = setOf("one", "two", "three")
    val lengths = strings.map { it.length }
    println(lengths)
}

Output

[3, 3, 5]

3 Transforming a set of custom objects

Using map() to transform a set of custom objects by extracting a specific property.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use map() with a transform function that extracts a specific property from each object.
  4. Print the resulting list.

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 names = people.map { it.name }
    println(names)
}

Output

[Alice, Bob, Charlie]

Summary

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.