Kotlin Tutorials

Kotlin Set forEachIndexed()
Syntax & Examples

Set.forEachIndexed() extension function

The forEachIndexed() extension function in Kotlin performs the given action on each element in the set, providing the sequential index along with the element.


Syntax of Set.forEachIndexed()

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

fun <T> Set<T>.forEachIndexed(action: (index: Int, T) -> Unit)

This forEachIndexed() extension function of Set performs the given action on each element, providing sequential index with the element.

Parameters

ParameterOptional/RequiredDescription
actionrequiredA function that takes the index and an element, and performs an action on them.

Return Type

Set.forEachIndexed() returns value of type Unit.



✐ Examples

1 Printing each element with its index

Using forEachIndexed() to print each element in a set with its index.

For example,

  1. Create a set of strings.
  2. Use forEachIndexed() to print each element with its index.

Kotlin Program

fun main() {
    val strings = setOf("a", "b", "c")
    strings.forEachIndexed { index, value -> println("$index: $value") }
}

Output

0: a
1: b
2: c

2 Printing each element's double with its index

Using forEachIndexed() to print each element's double in a set with its index.

For example,

  1. Create a set of integers.
  2. Use forEachIndexed() to print each element's double with its index.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    numbers.forEachIndexed { index, value -> println("$index: ${value * 2}") }
}

Output

0: 2
1: 4
2: 6
3: 8
4: 10

3 Printing each element and its square with its index

Using forEachIndexed() to print each element and its square in a set with its index.

For example,

  1. Create a set of integers.
  2. Use forEachIndexed() to print each element and its square with its index.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    numbers.forEachIndexed { index, value -> println("$index: $value, ${value * value}") }
}

Output

0: 1, 1
1: 2, 4
2: 3, 9
3: 4, 16
4: 5, 25

Summary

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