Kotlin program: Convert list of strings to uppercase with lambda
Write a Kotlin program that implements a lambda expression to convert a list of strings to uppercase.
Pre-Knowledge (Before You Start!)
Before solving this exercise, you should be familiar with the following concepts:
- Lambda Expressions: A lambda expression is an anonymous function that allows concise operations on collections.
- String Manipulation: The uppercase() function converts a string to uppercase.
- Mapping Collections: The map() function transforms each element in a collection based on a given lambda expression.
- Iteration: The forEach function is used to iterate through a list and perform an operation on each element.
Hints (Try Before Looking at the Solution!)
Here are some hints to help you solve the problem:
- Hint 1: Create a list of lowercase strings.
- Hint 2: Use the map() function to apply a transformation to each string.
- Hint 3: Inside the lambda expression, use the uppercase() function to convert each string to uppercase.
- Hint 4: Store the transformed list in a variable.
- Hint 5: Use forEach to iterate over the transformed list and print each string on a new line.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics