Kotlin Collections & Operations
All Kotlin collection operations you should know
In this article, We will be discussing some of the Kotlin collection operations that a Kotlin developer, Android developer, should know to leverage the immense resources provided by the language.
It is assumed that you understand the difference between the mutable and immutable collections, including lists, maps and sets.
ForEach, forEachIndexed & withIndex
The forEach lambda function iterates through a list and provides access to each element. Inside the lambda block, an element can be accessed directly. In the example mentioned above, the integer element is accessed.
As mentioned above, the forEachIndexed lambda function provides access to both an element and its index in a given list. More importantly, forEachIndexed uses a local variable to keep the index count.
The withIndex returns a lazy Iterable that wraps each element of the original array into an IndexedValue containing the index of that element and the element itself.
Map, MapNotNull & MapIndexed
Kotlin map for collection returns a new collection with the transformation function applied to the elements in the original collection.
The mapNotNull returns a new collection containing non-null values after applying the transformation to the elements of the original collection.
The mapIndexed returns a new collection after applying the transformation provided to the elements of the original collection with the current index.
Filter, FilterNot, FilterNotNull() & Partition
The filter collection operation returns a new collection of elements after matching the predicate given with the elements in the original collection.
The filterNot operation returns a new collection of items that do not satisfy the predicate provided.
After matching the provided predicate, the partition operation returns a pair of collections separating elements into two groups. The first collection consists of elements that satisfy the predicate, and the second collection consists of the rest of the elements. If we declare the type of the partition result explicitly, it will be Pair<List<T>, List<T>>. In the below example, it is Pair<List<Int>, List<Int>>
filterIsInstance returns a new collection with a specific type of elements specified in the argument provided that are extracted from the original collection.
In the next part, more Kotlin collection operations will be discussed.