How to filter a list in Kotlin
Overview
A list is an ordered collection of elements. In this shot, we will learn how to filter a list in Kotlin.
The filter method in Kotlin filters the elements in the list with certain criteria. We pass lambda expressions to the filter with conditions.
Syntax
list.filter{//condition}
Example
In this example, we will filter out the odd numbers from a list of numbers.
fun main(){//The given numbersval nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)//Filtering the odd numbersval oddNums = nums.filter{ it % 2 != 0 }//Displaying the odd numbersprint(oddNums)}
Explanation
- Line 1: We define the
main()function. It is mandatory to define this function because the program execution starts from it. We write our further code in this main function. - Line 4: We declare and initialize the list of numbers,
nums. - Line 7: We filter the odd numbers using the
filtermethod on thenumslist. We store the returned numbers in theoddNumsvariable. - Line 10: We display the
oddNumslist.