Kotlin – Filter non-empty strings in a List
To filter non-empty strings in a list in Kotlin, you can use List.filter() function.
The following is a step by step process to filter non-empty strings in a List in Kotlin.
- Consider that we are given a list of string values in words list.
- Call filter() function on the words list, and specify the predicate to filter only non-empty strings. The predicate would be
it.length > 0
whereit
is a string value from list. - The filter() function returns a new list with the string values from words list that are non-empty strings.
Program
fun main() {
val words = listOf("apple", "banana", "", "cherry", "", "elderberry", "", "")
val result = words.filter { it.length > 0 }
println(result)
}
Output
[apple, banana, cherry, elderberry]