Apply a function to each element of a List in Kotlin
This article explores different ways to apply a function to each element of a List in Kotlin.
1. Using map() function
The standard approach to apply a given function to the elements of the list is using the map() function. This solution should be used to get a new list, leaving the original list unchanged.
|
1 2 3 4 5 6 |
fun main() { val words = listOf("A", "B", "C", "D") val caps = words.map { it.toLowerCase() } println(caps) } |
Output:
[a, b, c, d]
2. Using replaceAll() function
If you need to in-place transform a list, consider using the replaceAll() function instead of map(). The replaceAll() function can apply a specified function to each element of the list, as shown below:
|
1 2 3 4 5 6 |
fun main() { val words = mutableListOf("A", "B", "C", "D") words.replaceAll { it.toLowerCase() } println(words) } |
Output:
[a, b, c, d]
3. Using Loop
You can also write our own routine for this simple task. The idea is to iterate over the list using a loop, and transform each encountered element, and insert the element in a new list. This logic would translate to the following code:
|
1 2 3 4 5 6 7 8 9 |
fun main() { val words = listOf("A", "B", "C", "D") val caps: MutableList<String> = mutableListOf() for (word in words) { caps.add(word.toLowerCase()) } println(caps) } |
Output:
[a, b, c, d]
That’s all about applying a function to each element of a List in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)