Kotlin – Filter odd numbers in list

Kotlin – Filter odd numbers in a List

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

The following is a step by step process to filter odd 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 odd numbers. The predicate would be it % 2 == 1 where it is element from list.
  3. The filter() function returns a new list with the integer values from numbers list that are odd numbers.

Program

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

    val oddNumbers = numbers.filter { it % 2 == 1 }

    println(oddNumbers)
}

Output

[1, 3, 5, 7, 9]