Kotlin – Filter non-empty strings in List

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.

  1. Consider that we are given a list of string values in words list.
  2. Call filter() function on the words list, and specify the predicate to filter only non-empty strings. The predicate would be it.length > 0 where it is a string value from list.
  3. 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]