Kotlin List forEach
The Kotlin forEach() function performs an action for every element in a list, in iteration order. The action is written as a lambda expression. Inside a lambda with one parameter, the current list element can be referenced using the implicit name it.
Use forEach() when every element requires the same action, such as printing values, updating a total, or passing each item to another function. When the index is also required, use forEachIndexed().
Kotlin List forEach() Syntax
The syntax of the List.forEach() function is:
theList.forEach {
//statement(s)
}
The lambda passed to forEach() runs once for each element. The function returns Unit, so it is intended for performing actions rather than producing a transformed list.
You can replace it with an explicit parameter name when that makes the code easier to read.
theList.forEach { item ->
// use item here
}
Kotlin List forEach() with String Elements
The following example prints every element of a List<String>. During each invocation of the lambda, it contains the current string.
Kotlin Program
fun main(args: Array<String>) {
var listB = listOf<String>("Example", "Program", "Tutorial")
listB.forEach {
println(it)
}
}
Output
Example
Program
Tutorial
The elements are printed in the same order in which they occur in the list.
Kotlin List forEach() with Integer Elements
The next example uses forEach() with a List<Int>. The current integer is passed to println() during each iteration.
Kotlin Program
fun main(args: Array<String>) {
var listB = listOf<Int>(8, 56, 12, 42)
listB.forEach {
println(it)
}
}
Output
8
56
12
42
Calculate a Total with Kotlin List forEach()
A variable declared outside the lambda can be updated while processing the elements. The following example calculates the sum of the numbers in a list.
fun main() {
val prices = listOf(25, 40, 15)
var total = 0
prices.forEach { price ->
total += price
}
println("Total: $total")
}
Total: 80
For a simple numeric total, Kotlin also provides functions such as sum() and sumOf(). Use those functions when they express the intended calculation more directly.
Kotlin List forEach() with Custom Objects
A list can contain instances of a class or data class. Inside forEach(), access the properties of the current object through it or a named lambda parameter.
Kotlin Program
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
The first Book uses the default price of 0. The second object supplies 2 as its price.
Kotlin forEachIndexed() for List Index and Value
Use forEachIndexed() when the action needs both the zero-based index and the element. Its lambda receives the index first and the element second.
theList.forEachIndexed { index, item ->
// use index and item
}
The following example prints numbered task labels. Because indexes start at zero, the displayed position uses index + 1.
fun main() {
val tasks = listOf("Plan", "Write", "Review")
tasks.forEachIndexed { index, task ->
println("${index + 1}. $task")
}
}
1. Plan
2. Write
3. Review
Kotlin forEach() with a Map
Kotlin also provides forEach() for maps. A map iteration processes each key-value entry. Destructuring the entry into key and value keeps the lambda concise.
fun main() {
val scores = mapOf(
"Asha" to 84,
"Ravi" to 76,
"Meera" to 91
)
scores.forEach { (name, score) ->
println("$name: $score")
}
}
Asha: 84
Ravi: 76
Meera: 91
Skip an Element in Kotlin forEach() with a Labeled Return
Kotlin does not permit continue directly inside a forEach() lambda. A local labeled return, written as return@forEach, finishes the current lambda invocation and continues with the next element.
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
numbers.forEach {
if (it == 3) return@forEach
println(it)
}
}
1
2
4
5
The value 3 is skipped, but processing continues with 4 and 5. A plain return inside this inline lambda can return from the enclosing function, so use labeled returns deliberately.
Stop Kotlin List Iteration: for Loop Instead of forEach()
forEach() does not provide a direct equivalent of break. When iteration must stop as soon as a condition is met, a regular for loop is usually clearer.
fun main() {
val numbers = listOf(4, 8, 12, 16)
for (number in numbers) {
if (number == 12) break
println(number)
}
}
4
8
Functions such as firstOrNull(), find(), takeWhile(), and any() may also be appropriate when the goal is searching or conditional selection rather than performing side effects.
Kotlin for Loop vs List forEach()
| Requirement | Preferred Kotlin construct |
|---|---|
| Perform an action for every list element | forEach() |
| Use both index and value | forEachIndexed() |
Exit iteration with break | for loop |
Skip an iteration with continue | for loop, or return@forEach when appropriate |
| Create a transformed list | map() |
| Select matching elements | filter() |
| Find the first matching element | find() or firstOrNull() |
Neither form is a universal replacement for the other. Choose the construct that most directly represents the operation being performed.
Transform List Elements with map() Instead of forEach()
Use map(), not forEach(), when the required result is a new list containing transformed elements. Although values can be manually appended to another list inside forEach(), map() communicates that transformation directly.
fun main() {
val names = listOf("asha", "ravi", "meera")
val uppercaseNames = names.map { it.uppercase() }
println(uppercaseNames)
}
[ASHA, RAVI, MEERA]
Adding Items While Iterating a Kotlin List
Avoid structurally modifying the same mutable list while forEach() is iterating over it. Depending on the list implementation and operation, this can cause incorrect behavior or a ConcurrentModificationException.
If new values must be produced during iteration, collect them separately and add them after the iteration finishes.
fun main() {
val numbers = mutableListOf(1, 2, 3)
val additions = mutableListOf<Int>()
numbers.forEach { number ->
additions.add(number * 10)
}
numbers.addAll(additions)
println(numbers)
}
[1, 2, 3, 10, 20, 30]
If the desired result is simply a transformed collection, map() is usually shorter and avoids mutating either list during iteration.
Kotlin List forEach() Frequently Asked Questions
What does it mean inside Kotlin forEach()?
it is Kotlin’s implicit name for the single parameter of a lambda expression. In list.forEach { println(it) }, it represents the current list element. You can replace it with an explicit name, such as list.forEach { item -> println(item) }.
How do I get the index in Kotlin list forEach()?
Use forEachIndexed { index, item -> ... }. The index starts at 0 and is supplied together with the corresponding element.
Can I use break or continue inside Kotlin forEach()?
break and continue are not used directly in a forEach() lambda. Use return@forEach to skip the current element. Use a regular for loop when you need break or conventional continue behavior.
Does Kotlin forEach() return a new list?
No. forEach() performs an action and returns Unit. Use map() to create a transformed list or filter() to create a list containing matching elements.
Can Kotlin forEach() be used with a MutableList?
Yes. Both read-only and mutable lists are iterable, so both support forEach(). However, avoid adding or removing elements from the same mutable list during its iteration.
Kotlin List forEach() Tutorial QA Checklist
- Verify that each
forEach()example performs an action for every element in list order. - Confirm that
itis described as the implicit single lambda parameter, not as a special list variable. - Check that examples requiring an index use
forEachIndexed()with the index parameter first. - Ensure that
return@forEachis explained as skipping the current lambda invocation rather than terminating the complete iteration. - Confirm that examples requiring
breakuse a regularforloop and that transformations usemap()instead of unnecessary side effects.
Summary of Kotlin List forEach()
In this Kotlin Tutorial on Kotlin list forEach, we learned how to perform an action for each string, integer, or custom object in a list. We also covered named lambda parameters, forEachIndexed(), map iteration, labeled returns, the difference between forEach() and a for loop, and safe handling of mutable lists during iteration.
TutorialKart.com