Kotlin Program: Filter list of strings with lambda expression
Kotlin Lambda: Exercise-5 with Solution
Write a Kotlin program that implements a lambda expression to filter a list of strings. It returns only strings starting with the letter 'K'.
Sample Solution:
Kotlin Code:
fun main() {
val strings = listOf("Kotlin", "Java", "Kotlin Programming", "Python", "Kotlin Language")
val filteredList = strings.filter { it.startsWith("K") }
println("Filtered List:")
filteredList.forEach { println(it) }
}
Sample Output:
Filtered List: Kotlin Kotlin Programming Kotlin Language
Explanation:
In the above exercise -
- We have a list of strings called strings. We use the "filter()" function on the strings list and provide a lambda expression { it.startsWith("K") } as the filter condition.
- Inside the lambda expression, we use the startsWith function to check if each string in the list starts with the letter 'K'. If it does, the string is included in the filtered list.
- Finally, we print the filtered list using a combination of println and forEach to iterate over each string in the filtered list.
Kotlin Editor:
Previous: Lambda expression for calculating the average of numbers.
Next: Sort integer list in descending order with lambda.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics