Kotlin Tutorials

Kotlin Set mapIndexed()
Syntax & Examples

Set.mapIndexed() extension function

The mapIndexed() extension function in Kotlin returns a list containing the results of applying the given transform function to each element and its index in the original set.


Syntax of Set.mapIndexed()

The syntax of Set.mapIndexed() extension function is:

fun <T, R> Set<T>.mapIndexed(transform: (index: Int, T) -> R): List<R>

This mapIndexed() extension function of Set returns a list containing the results of applying the given transform function to each element and its index in the original collection.

Parameters

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

Return Type

Set.mapIndexed() returns value of type List.



✐ Examples

1 Transforming a set of integers by adding their indices

Using mapIndexed() to transform a set of integers by adding their indices to each element.

For example,

  1. Create a set of integers.
  2. Use mapIndexed() with a transform function that adds the index to each element.
  3. Print the resulting list.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val indexed = numbers.mapIndexed { index, value -> index + value }
    println(indexed)
}

Output

[1, 3, 5, 7, 9]

2 Transforming a set of strings by concatenating their indices

Using mapIndexed() to transform a set of strings by concatenating their indices to each string.

For example,

  1. Create a set of strings.
  2. Use mapIndexed() with a transform function that concatenates the index to each string.
  3. Print the resulting list.

Kotlin Program

fun main() {
    val strings = setOf("one", "two", "three")
    val indexedStrings = strings.mapIndexed { index, value -> "$index: $value" }
    println(indexedStrings)
}

Output

[0: one, 1: two, 2: three]

3 Transforming a set of custom objects by including their indices

Using mapIndexed() to transform a set of custom objects by including their indices in the transformation.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use mapIndexed() with a transform function that includes the index in the transformation.
  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 indexedPeople = people.mapIndexed { index, person -> "$index: ${person.name}, ${person.age}" }
    println(indexedPeople)
}

Output

[0: Alice, 30, 1: Bob, 25, 2: Charlie, 35]

Summary

In this Kotlin tutorial, we learned about mapIndexed() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.