The filter function

Think of a situation where you need to filter the items in a collection. For example, when you want to obtain only even numbers from a list of integers. The filter function is there to help you in these scenarios.

The filter function receives all the elements of the collection as each iteration and should return true or false, based on its determination of whether the passed item should be on the resultant list or not.

Go through the following program:

fun main(args: Array<String>) { 
    val list = 1.until(50).toList()//(1) 
    val filteredListEven = list.filter { it%2==0 }//(2) 
 
    println("filteredListEven -> $filteredListEven") 
 
    val filteredListPSquare = list.filter { 
        val sqroot = sqrt(it.toDouble()).roundToInt() 
        sqroot*sqroot==it 
    }//(3) 
 
    println("filteredListPSquare -> $filteredListPSquare") 
} 

In this program, we first obtained a list of Int containing numbers from 1 to 50 with the help of IntRange. We then filtered the list to obtain even numbers on comment (2) and printed them. On comment (3), we filtered the list (the original list containing Int values from 1 to 50) to obtain perfect squares and printed them.

The following is the output of the program:

The previous code snippet and its output show just how much boilerplate code can be eliminated with the help of these data operation functions.

..................Content has been hidden....................

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