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.
list.filter{//condition}
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)}
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.nums
.filter
method on the nums
list. We store the returned numbers in the oddNums
variable.oddNums
list.