Kotlin List – Filter Odd Numbers

To filter odd numbers of a Kotlin List, call filter() function on this Integers List and pass the predicate: the element should be an odd 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 odd numbers.

Examples

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

Main.kt

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("Odd Numbers in 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 odd, or false if x is not odd.

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]
Odd Numbers in List : [1, 5, 9, 33]

Conclusion

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