Kotlin Tutorials

Kotlin Set forEach()
Syntax & Examples

Set.forEach() extension function

The forEach() extension function in Kotlin performs the given action on each element in the set.


Syntax of Set.forEach()

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.

Parameters

ParameterOptional/RequiredDescription
actionrequiredA function that takes an element and performs an action on it.

Return Type

Set.forEach() returns value of type Unit.



✐ Examples

1 Printing each element

Using forEach() to print each element in a set.

For example,

  1. Create a set of integers.
  2. Use forEach() to print each element in the set.

Kotlin Program

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

Output

1
2
3
4
5

2 Doubling each element

Using forEach() to double each element in a set and print the result.

For example,

  1. Create a set of integers.
  2. Use forEach() to double each element and print the result.

Kotlin Program

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

Output

2
4
6
8
10

3 Printing each element with its index

Using forEach() 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

Summary

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.