Skip to content

Kotlin forEach list

  • by

1. Overview

In this article, we will discuss the Kotlin forEach list function used in collections.

2. forEach

If you want to do any action on each of the collection elements, then you can use this Kotlin forEach list function. Let’s see different use cases to understand this better.

2.1. forEach for array

The syntax of forEach function for the array is

inline fun <T> Array<out T>.forEach(action: (T) -> Unit)

This forEach function takes a predicate as a parameter and the predicate determines the action to be performed on each of the array element. Suppose you have a list of 5 square numbers and you want to print the square root of each of these numbers. To achieve this, you can use the forEach function to print square root of each element. Create a predicate with code to calculate the square root and print statement and pass it as a parameter to the forEach function.

var squares = listOf(1, 4, 9, 16, 25)

squares.forEach {
   println("Sqrt of " + it + " is " + sqrt(it.toDouble()))
}

Result:

Sqrt of 1 is 1.0
Sqrt of 4 is 2.0
Sqrt of 9 is 3.0
Sqrt of 16 is 4.0
Sqrt of 25 is 5.0

2.2. forEach for Map

The syntax of forEach function for the Map is

inline fun <K, V> Map<out K, V>.forEach(
    action: (Entry<K, V>) -> Unit)

As mentioned before, forEach determines the action to be performed on each element of Map. Let’s consider you have a map with natural numbers as key and their corresponding square as value. And you want to iterate and print each of the map element. Here, you can use forEach function to print each element and its square in console.

val squares = mapOf(1 to 1, 2 to 4, 3 to 9, 4 to 16, 5 to 25)

squares.forEach {
    println("Square of " + it.key + " is " + it.value)
}

Result:

Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25

2.3 forEach for Iterator

The syntax of forEach for Iterator is

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

This forEach function performs the operation on each element of the Iterator.

Let’s see the same sqrt example to understand how forEach works with Iterator. Now, we have a list of 5 square numbers and create an Iterator to iterate the elements. You can use forEach on the Iterator and print all the square root of each square number in the Iterator.

val squares = listOf(1, 4, 9, 16, 25)
val iterator = squares.listIterator()
iterator.forEach {
   println("Sqrt of " + it + " is " + sqrt(it.toDouble()))
}

Result:

Sqrt of 1 is 1.0
Sqrt of 4 is 2.0
Sqrt of 9 is 3.0
Sqrt of 16 is 4.0
Sqrt of 25 is 5.0

3. Conclusion

In this article, we have seen the forEach function and few examples to understand its usage.

Leave a Reply

Your email address will not be published. Required fields are marked *