Kotlin List onEach()
Syntax & Examples
Syntax of List.onEach()
The syntax of List.onEach() extension function is:
fun <T, C : Iterable<T>> C.onEach(action: (T) -> Unit): C
This onEach() extension function of List performs the given action on each element and returns the collection itself afterwards.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing the integers[1, 2, 3, 4, 5]
. - We apply the
onEach
function to the list, which prints each element to the console. - The
onEach
function returns the original list. - Finally, we print the original list to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5);
val newList = list.onEach { println(it) };
println(newList);
}
Output
1 2 3 4 5 [1, 2, 3, 4, 5]
2 Example
In this example,
- We create a list named
list
containing the characters['a', 'b', 'c', 'd', 'e']
. - We apply the
onEach
function to the list, which prints the uppercase of each character to the console. - The
onEach
function returns the original list. - Finally, we print the original list to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c', 'd', 'e');
list.onEach { print(it.toUpperCase()) };
}
Output
ABCDE
3 Example
In this example,
- We create a list named
list
containing the strings['apple', 'banana', 'orange', 'grape']
. - We apply the
onEach
function to the list, which prints the uppercase of each string to the console. - The
onEach
function returns the original list. - Finally, we print the original list to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "orange", "grape");
list.onEach { println(it.toUpperCase()) };
}
Output
APPLE BANANA ORANGE GRAPE
Summary
In this Kotlin tutorial, we learned about onEach() extension function of List: the syntax and few working examples with output and detailed explanation for each example.