Kotlin List - forEach() Function



The Kotlin List forEach() function is used to loops across the list, and it is easier to perform the given operation or action on each element of list.

There are the following use cases of the forEach() function:

  • Iterate through a Collection: It simplifies iteration by applying a given lambda function to each element.
  • Perform Operation: We can perform custom operation on each element, like logging, transformation, and validation.
  • Improve Code Readability: As compared to traditional for loop. ForEach result is cleaner and more concise.

Syntax

Following is the syntax of Kotlin list forEach() function −

inline fun <T> List<T>.forEach(operation: (T) -> Unit)

Parameters

This function accepts a lambda function as a parameter that specifies the operation to be performed on each element.

Return value

This function does not return any values.

Example 1: Iterating Over a List

Let's see a basic example of the forEach() function, which display the elements of list.

fun main() {
   val numbers = listOf(1, 2, 3, 4, 5)
   // Print each element
   numbers.forEach { println(it) }
}

Output

Following is the output −

1
2
3
4
5

Example 2: Perform Operation on Each Element

The following example uses forEach() function to perform an action on each element in list −

fun main() {
   val names = listOf("Aman", "Rahul", "Akash")
   names.forEach { name ->
      println("Hello, $name!")
   }
}

Output

Following is the output −

Hello, Aman!
Hello, Rahul!
Hello, Akash!

Example 3: Modify External Variable

This is another example of forEach() function to modify value of the variable sum −

fun main(args: Array<String>){
   val numbers = listOf(1, 2, 3, 4, 5)
   var sum = 0
   numbers.forEach { sum += it }
   println("Sum of numbers: $sum")
}

Output

Following is the output −

Sum of numbers: 15
kotlin_lists.htm
Advertisements