Kotlin List forEach

Kotlin List foreach is used perform the given action on each item of the list. Inside the code block of forEach, the item could be referenced as it.

Syntax – List forEach

The syntax of List.forEach() method is

</>
Copy
theList.forEach {
    //statement(s)
}

Example 1 – Kotlin List forEach – String

In the following example, we shall print each item of String List using forEach.

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    var listB = listOf<String>("Example", "Program", "Tutorial")

    listB.forEach {
        println(it)
    }
}

Output

Example
Program
Tutorial

Example 2 – Kotlin List forEach – Integer

In the following example, we shall print each item of an Integer List using forEach.

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    var listB = listOf<Int>(8, 56, 12, 42)

    listB.forEach {
        println(it)
    }
}

Output

8
56
12
42

Example 3 – Kotlin List forEach – Custom Object

In the following example, we shall consider list of Data Class objects and print a message for each item of the List using forEach.

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    val book1 = Book("Kotlin Tutorial")
    val book2 = Book("Kotlin Android Tutorial", 2)
    var listB = listOf<Book>(book1, book2)

    listB.forEach {
        println("Price of book, ${it.name} is ${it.price}")
    }
}

data class Book(val name: String = "", val price: Int = 0)

Output

Price of book, Kotlin Tutorial is 0
Price of book, Kotlin Android Tutorial is 2

Conclusion

In this Kotlin TutorialKotlin list forEach, we have learnt how to perform a block of statement for each element of the list, with examples.