Exploring Kotlin standard library extensions functions to retrieving parts of a kotlin collections.
Collections are the integral parts of any programing language. Kotlin has an amazing Standard library, which provides tools support to manage Kotlin Collection in a great way! Check out more about Kotlin Collection in Kotlin Collections — Introduction (part-1).
What we are going to learn:
In this blog, we will deep dive into how we can retrieve specific parts of Collection. In other words, we can say we will check different extension functions that help us to retrieve Collections elements using a specific range of indices.
Kotlin standard library extension functions
1. Take and drop
1. take(): To take a specific number of elements from the starting:
2. takeLast(): To take the number of elements from the last positions:
2. drop(): To get all the elements except a given number of first elements:
4. dropLast(): To get all the elements except a given number of last elements:
In addition, the Standard Library provides functions with conditions to take and drop elements. Below all functions are using predicates which use for taking or dropping the elements:
1. takeWhile(): is take() with a predicate: it takes the elements up to but excluding the first one not matching the predicate. If the first collection element doesn’t match the predicate, the result is empty.
2. takeLastWhile(): It is similar to takeLast() but with matching predicates. If the last collection element doesn’t match the predicate, the result is empty.
3. dropWhile(): it returns the elements from the first one not matching the predicate to the end. opposite to takeWhile().
4. dropLastWhile(): it returns the elements from the last one not matching the predicate to the end. opposite to takeLastWhile().
1. slice(): Retrieve collections of elements using indices. Indices may be passed either as a range(0..2) or as a collection of integer values.
Using chunked(), we can break the collection into parts. It will return the list of lists using a chunk size given in the argument.
Using windowed() return all possible ranges of the collection elements of a given size.
So, that was pretty cool, right? This is all the stuff you need to know about Retrieving parts from Kotlin Collections using Kotlin standard library.
Check out more details about Kotlin Collection parts here.
About me: https://pranaypatel512.github.io/