The forEachIndexed() extension function in Kotlin performs the given action on each element in the set, providing the sequential index along with the element.
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.
Parameter | Optional/Required | Description |
---|---|---|
action | required | A function that takes the index and an element, and performs an action on them. |
Set.forEachIndexed() returns value of type Unit
.
Using forEachIndexed() to print each element in a set with its index.
For example,
fun main() {
val strings = setOf("a", "b", "c")
strings.forEachIndexed { index, value -> println("$index: $value") }
}
0: a 1: b 2: c
Using forEachIndexed() to print each element's double in a set with its index.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
numbers.forEachIndexed { index, value -> println("$index: ${value * 2}") }
}
0: 2 1: 4 2: 6 3: 8 4: 10
Using forEachIndexed() to print each element and its square in a set with its index.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
numbers.forEachIndexed { index, value -> println("$index: $value, ${value * value}") }
}
0: 1, 1 1: 2, 4 2: 3, 9 3: 4, 16 4: 5, 25
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.