The forEach() extension function in Kotlin performs the given action on each element in the set.
The syntax of Set.forEach() extension function is:
fun <T> Set<T>.forEach(action: (T) -> Unit)
This forEach() extension function of Set performs the given action on each element.
Parameter | Optional/Required | Description |
---|---|---|
action | required | A function that takes an element and performs an action on it. |
Set.forEach() returns value of type Unit
.
Using forEach() to print each element in a set.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
numbers.forEach { println(it) }
}
1 2 3 4 5
Using forEach() to double each element in a set and print the result.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
numbers.forEach { println(it * 2) }
}
2 4 6 8 10
Using forEach() 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
In this Kotlin tutorial, we learned about forEach() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.