In this tutorial, you shall learn how to filter non-empty strings in a list in Kotlin using List.filter() function, with examples.

Kotlin List – Filter Non-Empty Strings

To filter non-empty String elements of a Kotlin List, call filter() function on this String List and pass the predicate: String length greater than zero or String element is not Empty String; as parameter for the filter() function..

In this tutorial, we will learn how to use filter() function on a List of Strings, and filter the non-empty Strings.

Example

In the following program, we will take a List of Strings and filter only non-empty strings with the condition that the length of a String element is greater than 0.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    var myList = listOf("", "apple", "", "banana" ,"", "orange", "", "")
    var filteredList = myList.filter { x -> x.length > 0 }
    println("Original List : ${myList}")
    println("Filtered List : ${filteredList}")
}

Output

Original List : [, apple, , banana, , orange, , ]
Filtered List : [apple, banana, orange]

Or we can also use the condition that the String is not empty String, as shown in the following program.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    var myList = listOf("", "apple", "", "banana" ,"", "orange", "", "")
    var filteredList = myList.filter { x -> x != "" }
    println("Original List : ${myList}")
    println("Filtered List : ${filteredList}")
}

Output

Original List : [, apple, , banana, , orange, , ]
Filtered List : [apple, banana, orange]

Conclusion

In this Kotlin Tutorial, we learned how to filter only non-empty Strings of a List using filter() function, with the help of examples.