To filter elements of a list based on a condition in Kotlin, you can use the filter
function.
In this example,
numbers
with integer values.filter
function to filter elements greater than a threshold value.fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
val threshold = 3
val filteredNumbers = numbers.filter { it > threshold }
println("Filtered list: $filteredNumbers")
}
Filtered list: [4, 5]
In this example,
words
with string values.filter
function to filter elements containing a specific substring.fun main() {
val words = listOf("apple", "banana", "cherry", "date", "elderberry")
val substring = "erry"
val filteredWords = words.filter { it.contains(substring) }
println("Filtered list: $filteredWords")
}
Filtered list: [cherry, elderberry]
In this tutorial, we learned How to Filter Elements of a List based on a Condition in Kotlin language with well detailed examples.