Kotlin List – Filter Even Numbers

To filter even numbers of a Kotlin List, call filter() function on this Integers List and pass the predicate: the element should be an even number; to the filter() function as parameter.

In this tutorial, we will learn how to use filter() function on a List of integers, and filter only even numbers.

Examples

In the following program, we will take a List of Integers and filter only even numbers.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    var myList = listOf(1, 4, 8, 5, 6, 9, 12, 10, 33)
    var filteredList = myList.filter { x -> x % 2 == 0 }
    println("Original List : ${myList}")
    println("Filtered List : ${filteredList}")
}

Here, the lambda function: { x -> x % 2 == 0 } is the predicate to the filter() function. This predicate returns true if the element x is even, or false if x is not even.

For each element x in the List, only those elements that satisfy the condition x % 2 == 0 are returned in the resulting List.

Output

Original List : [1, 4, 8, 5, 6, 9, 12, 10, 33]
Filtered List : [4, 8, 6, 12, 10]

Conclusion

In this Kotlin Tutorial, we learned how to filter only even numbers of an Integer List using filter() function, with the help of examples.