In this tutorial, you shall learn how to filter only string elements in a list in Kotlin using List.filterIsInstance() function, with examples.

Kotlin – Filter only Strings in this List

A Kotlin List of type Any can store elements of any type. To filter elements of only type String, call filterIsInstance() method on this method, with the type T specified as String for filterIsInstance<T>() function.

The syntax to filter only String elements of a List<Any> is

List.filterIsInstance<String>()

filterIsInstance<String>() returns a List. The returned list contains only the String elements in this List, if any.

Example

In the following program, we will take a List of Elements of different types, and filter only those elements whose type is String.

Main.kt

fun main(args: Array<String>) {
    var myList: List<Any> = listOf(4, true, "abcd", 0.2 ,"four")
    var filteredList = myList.filterIsInstance<String>()
    println("Original List : ${myList}")
    println("Filtered List : ${filteredList}")
}

Output

Original List : [4, true, abcd, 0.2, four]
Filtered List : [abcd, four]

Only the String elements in the given list are returned in the filtered list.

ADVERTISEMENT

Conclusion

In this Kotlin Tutorial, we learned how to filter only String elements of a List<Any> using filterIsInstance() function, with the help of examples.