Kotlin | Retrieve Collection Parts
Kotlin provides extension functions for retrieving collection parts. A member function defined outside the class is called an extension function. These extension functions can provide a variety of ways to select different items from the list.
Four extension functions are:
- Slice
- Take and Drop
- Chunked
- Windowed
Slice
Slice functions work just like in other languages which returns a list of items with given indices. These indices can be passed as range or integer values.
Kotlin example to demonstrate slice –
fun main(args: Array<String>) { val fruits = listOf("apple", "banana", "cherries", "dragon_fruit", "egg_fruit", "fig") println(fruits.slice(1..4)) println(fruits.slice(0..4 step 2)) println(fruits.slice(setOf(1, 2, 4))) } |
Output:
[banana, cherries, dragon_fruit, egg_fruit] [apple, cherries, egg_fruit] [banana, cherries, egg_fruit]
Take and Drop
As the name suggests take() function can take specified number of items from the start. If we want to grab items from last we can call takeLast() function.
Similarly, drop() function takes all items except the specified number of items from the start and dropLast() takes all the items except the specified number of items from the last.
Kotlin example to demonstrate take and drop –
fun main(args: Array<String>) { val fruits = listOf("apple", "banana", "cherries", "dragon_fruit", "egg_fruit", "fig") println(fruits.take(3)) println(fruits.takeLast(3)) println(fruits.drop(4)) println(fruits.dropLast(4)) } |
Output:
[apple, banana, cherries] [dragon_fruit, egg_fruit, fig] [egg_fruit, fig] [apple, banana]
There are four functions in take and drop with which we can use predicates to define number of items to take and drop.
Kotlin program –
fun main(args: Array<String>) { val fruits = listOf("apple", "banana", "cherries", "dragon_fruit", "egg_fruit", "fig") //takeWhile() takes the items upto but // excluding the first one not matching the predicate. println(fruits.takeWhile{!it.startsWith("d")}) //takeLastWhile() takes a range of items // matching the predicate from the end. println(fruits.takeLastWhile{it != "cherries"}) //dropWhile() returns the items from first // one not matching the predicate to the end. println(fruits.dropWhile{it.length == 5}) //dropWhileLast() returns element from the // beginning to the last one not matching the predicate. println(fruits.dropLastWhile{it.contains("i")}) } |
Output:
[apple, banana, cherries] [dragon_fruit, egg_fruit, fig] [banana, cherries, dragon_fruit, egg_fruit, fig] [apple, banana]
Chunked
Chunking is a function by which individual pieces of an list are broken down and then grouped together into specified chunk size. chunk() function takes a single argument an returns lists of that chunk size.
We can also apply transformation for the returned chunks. In order to do that, we provide the transformation as a lambda function when calling chunked(). When chunked() is called with a transformation, the chunks are short-living Lists that should be used in the lambda expression for another purpose.
Kotlin program of using chunk() function –
fun main(args: Array<String>) { val fruits = listOf("apple", "banana", "cherries", "dragon_fruit", "egg_fruit", "fig") // chunks into list size of three println(fruits.chunked(3)) // lambda function to sum the elements val numbers = (0..11).toList() println(numbers.chunked(3) { it.sum() }) } |
Output:
[[apple, banana, cherries], [dragon_fruit, egg_fruit, fig]] [3, 12, 21, 30]
Windowed
The windowed() function can fetch all possible ranges of collection of items on a given size. It returns a list of element ranges that you would see at the collection using sliding window of the particular size.
It has optional two parameters:
step: distance between first item of every window. By default the value is 1, so the result contains windows starting from all elements.
partialWindows: if true includes windows of smaller size left at the end.
Kotlin program to demonstrate windowed() function –
fun main(args: Array<String>) { val fruits = listOf("apple", "banana", "cherries","orange") println(fruits.windowed(3)) println(fruits.windowed(3, step = 2, partialWindows = true)) } |
Output:
[[apple, banana, cherries], [banana, cherries, orange]] [[apple, banana, cherries], [cherries, orange]]
There is a zipWithNext() function to build two element window, can also be called with a transformation.
Kotlin program to demonstrate zipWithNext() –
fun main(args: Array<String>) { val fruits = listOf("apple", "banana", "cherries", "dragon_fruit", "egg_fruit", "fig") println(fruits.zipWithNext()) } |
Output:
[(apple, banana), (banana, cherries), (cherries, dragon_fruit), (dragon_fruit, egg_fruit), (egg_fruit, fig)]
Recommended Posts:
- Retrieve Single Elements In Kotlin
- Kotlin | Collection Transformation
- Kotlin - Collection Operations Overview
- Kotlin Collection Write operations
- Retrieve the position (X,Y) of an element using HTML
- HTML | DOM applets Collection
- HTML | DOM scripts Collection
- HTML | DOM forms Collection
- HTML | DOM links Collection
- Defining, Creating and Dropping a MongoDB collection
- Kotlin String
- Kotlin Hashmap
- Kotlin Ranges
- Kotlin Map : mapOf()
- TimePicker in Kotlin
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : nidhi_biet

