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


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


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


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}")


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.


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