Kotlin Set - forEach() Function



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

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 set forEach() function −

inline fun <T>Set<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 Set

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

fun main() {
   val numbers = setOf(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 set −

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

Output

Following is the output −

Hii, Aman!
Hii, Rahul!
Hii, Akash!

Example 3: Modify External Variable

This is another example of forEach() function to modify the value of variable sum, but in set we can sum only distinct elements, not duplicates - −

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

Output

Following is the output −

Sum of numbers: 15
kotlin_sets.htm
Advertisements