Kotlin List.forEach() – Examples

Kotlin List.forEach()

The Kotlin List.forEach() function performs the given action on each element of the list.

Syntax

List.forEach(action)

You can access each item in the forEach block, using variable name it. This variable holds the specific item during that iteration.

Example 1

In this example,

  1. Take a list of strings.
  2. Use forEach() to count the length of each item and print the result.

Program

fun main(args: Array<String>) {
    val list1 = listOf("google", "apple", "bing")
    list1.forEach{
        val len = it.length
        println(len)
    }
}

Output

6
5
4

Example 2

In this example,

  1. Take a list of numbers.
  2. For each number in the list, find the square of the number, and print the result.

Program

fun main(args: Array<String>) {
    val list1 = listOf(1, 2, 3, 4, 5)
    list1.forEach{
        val squared = it*it
        println(squared)
    }
}

Output

1
4
9
16
25