The filter function  

This is the most commonly used function in Kotlin. The filter function takes one lambda expression, which takes one variable as an input and returns the same variable as a result. The filter function applies the lambda expression and returns a list as a result. Let's create a list of integers and apply some filters:

var numbers = listOf<Int>(1,2,3,4,5,6,7,8,9,10)

We can filter out all elements that are greater than five as follows:

var newList = numbers.filter{ i -> i > 5 }
println("Filter out greater than 5")
println(newList)

i represents the element in the list and i > 5 is a condition that filters the results. The lambda expression filters the elements and the filter function returns a new list. 

We can filter out all elements that are smaller than or equal to five as follows:

newList = numbers.filter { i -> i <= 5 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.174.23