The take functions

The take functions work in just the opposite way to the drop functions. You can take a selection from the collection and ignore the rest.

Have a look at the following program:

fun main(args: Array<String>) { 
    val list = 1.until(50).toList() 
 
    println("list.take(25) -> ${list.take(25)}")//(1) 
    println("list.takeLast(25) -> ${list.takeLast(25)}")//(2) 
    println("list.takeWhile { it<=10 } -> ${list.takeWhile { it<=10 }}")//(3) 
    println("list.takeLastWhile { it>=40 } -> ${list.takeLastWhile { it>=40 }}")//(4) 
} 

While statements on comment (1) and comment (2) are opposite to the drop functions earlier, they just take and print the 25 items from the list.

The statement on comment (3) is a bit different, here we used the takeWhile function. The takeWhile function takes a predicate and keeps taking items on the resultant collection while the predicate returns true; once the predicate returns false the takeWhile value will stop checking for any more items and will return the resultant collection.

The takeLastWhile values work in a similar way but in reverse.

The following is a screenshot of the output:

Let's now move ahead with the zip functions.

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

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