w3resource

Kotlin program: Convert list of strings to uppercase with lambda

Kotlin Lambda: Exercise-7 with Solution

Write a Kotlin program that implements a lambda expression to convert a list of strings to uppercase.

Sample Solution:

Kotlin Code:

fun main() {
    val strings = listOf("red", "green", "blue", "white", "orange", "black")

    val uppercaseList = strings.map { it.uppercase() }

    println("Uppercase List:")
    uppercaseList.forEach { println(it) }
}

Sample Output:

Uppercase List:
RED
GREEN
BLUE
WHITE
ORANGE
BLACK

Explanation:

In the above exercise -

  • We have a list of strings called "strings". We use the map function on the "strings" list and provide a lambda expression { it.toUpperCase() } as the mapping operation.
  • Inside the lambda expression, we call the toUpperCase function on each string (it) to convert it to uppercase.
  • The "map()" function applies the lambda expression to each element of the "strings" list and returns a new list with transformed uppercase strings.
  • Finally, we print the uppercase list using println and forEach to iterate over each string in the uppercase list. We print it on a separate line.

Kotlin Editor:


Previous: Sort integer list in descending order with lambda.
Next: Check palindrome string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/kotlin-exercises/lambda/kotlin-lambda-exercise-7.php