Kotlin List forEach()
Syntax & Examples
Syntax of List.forEach()
The syntax of List.forEach() extension function is:
fun <T> Iterable<T>.forEach(action: (T) -> Unit)
This forEach() extension function of List performs the given action on each element.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing strings representing fruits. - We use the
forEach
function to print each element of the list to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry");
list.forEach { println(it) };
}
Output
apple banana cherry
2 Example
In this example,
- We create a list named
list
containing integers. - We use the
forEach
function to print each element of the list to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(10, 20, 30);
list.forEach { println(it) };
}
Output
10 20 30
3 Example
In this example,
- We create a list named
list
containing characters representing alphabets. - We use the
forEach
function to print each element of the list to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c');
list.forEach { println(it) };
}
Output
a b c
Summary
In this Kotlin tutorial, we learned about forEach() extension function of List: the syntax and few working examples with output and detailed explanation for each example.