Kotlin – Filter even numbers in List

Kotlin – Filter even numbers in a List

To filter even numbers in a list in Kotlin, you can use List.filter() function.

The following is a step by step process to filter even numbers in a List in Kotlin.

  1. Consider that we are given a list of integer values in numbers list.
  2. Call filter() function on the numbers list, and specify the predicate to filter only even numbers. The predicate would be it % 2 == 0 where it is element from list.
  3. The filter() function returns a new list with the integer values from numbers list that are even numbers.

Program

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    val evenNumbers = numbers.filter { it % 2 == 0 }

    println(evenNumbers)
}

Output

[2, 4, 6, 8, 10]