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

Kotlin – Filter only Integers in this List

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

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

List.filterIsInstance<Int>()

filterIsInstance<Int>() returns a List. The returned list contains only the Int 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 Int.

Main.kt

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

Output

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

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

ADVERTISEMENT

Conclusion

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