Kotlin Program: Filter list of strings with lambda expression
Write a Kotlin program that implements a lambda expression to filter a list of strings. It returns only strings starting with the letter 'K'.
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 can be assigned to a variable or used inline.
- List Filtering: The filter() function is used to filter elements in a list based on a given condition.
- String Functions: The startsWith() function checks whether a string starts with a specific character or substring.
- List Iteration: The forEach function is used to iterate over the elements of a list and perform an action.
Hints (Try Before Looking at the Solution!)
Here are some hints to help you solve the problem:
- Hint 1: Create a list of strings containing different words.
- Hint 2: Use the filter() function with a lambda expression to check if each string starts with the letter 'K'.
- Hint 3: Inside the lambda expression, use the startsWith() function to perform the check.
- Hint 4: Store the filtered list in a variable.
- Hint 5: Iterate over the filtered list using forEach and print each element.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics