Kotlin

Kotlin Map Filters Examples

Modern programming languages like Kotlin, which can be employed to create a variety of apps, notably Android development, provide clear and dynamic syntax. The map and filter methods in Kotlin are higher-order functions that work with collections (such as lists, sets, or arrays) and let you change and filter the contents of those collections. Each element of a collection is subjected to a transformation by the Kotlin map function which then returns a new collection that contains the modified items. As an input, it accepts a lambda function that specifies the transformation to be employed for each member. The following provided code explanations highlight how the map function in Kotlin improves the code readability and conciseness.

Syntax:

fun <L, R> Iterable<T>.map(transform: (L) -> R): List<R>
  • L: It represents the type of elements in the original collection.
  • R: It represents the type of elements in the resulting collection.
  • transform: It is a lambda function that takes an element of type L and returns a transformed element of type R.

Example 1:

Let’s begin with the first code example of Kotlin to demonstrate the use of the “map” function. The following code snippet demonstrates the usage of the “map” function in Kotlin by calculating the cube of each element in a list and printing the resulting list. The code starts with the main() function declaration.

In the main function, the code begins by defining a list of numbers “n” with the values [2, 4, 1, 7, 5]. This list represents the original collection of numbers. Next, the “map” method is applied to the “n” list. The “map” method receives a lambda expression as a parameter. The lambda expression, in this instance, is { it * it * it }.

For each “it” element in the “n” list, the lambda expression calculates the cube of the element by multiplying it three times. The “It” keyword denotes the present element that is being handled. So, it * it * it represents the cube of each element in the list. The map function applies the lambda expression to each element in the list, generates a new list, and returns the resulting list. In this situation, the resulting list is assigned to the “cube” variable. Finally, the “println” statement is used to print the ”cube” list which contains the cube of each element from the original “n” list.

fun main() {

val n = listOf(2, 4, 1, 7, 5)

val cube = n.map { it * it * it }

println(cube) }

The output of this code must be [8, 64, 1, 343, 125] as depicted in the attached image:

Example 2:

Let’s use the map filter to perform another operation on the Kotlin list. The provided code example uses the “map” function in Kotlin to convert each string in the “L” list to uppercase. The code snippet starts with the main() method.

Within the main function, the code starts by defining the “L” list with the values [“Huda”, “nars”, “laura mercier”]. This list represents the initial collection of strings in Kotlin. The “println” statement is then used to print the original “L” list. It outputs [“Huda”, “nars”, “laura mercier”] as it is without any update.

Next, the “map” method is applied to the main “L” list. It’s time to use the lambda expression as a parameter of the “map” method. The lambda expression in this instance is { it.toUpperCase() }. The “it” keyword denotes the current element of a list that is being handled. For each “it” element in the “L” list, the “it.toUpperCase()”lambda expression converts the string to uppercase using the toUpperCase() function. The “map” function applies the lambda expression to each element in the list, yields a new list, and returns the resulting list to the UP variable.

Finally, the “println” statement is used to print the UP list which contains the uppercase versions of each element from the original “L” list. It outputs [“HUDA”, “NARS”, “LAURA MERCIER”]:

fun main() {

val L = listOf("Huda", "nars", "laura mercier")

println(L)

val UP = L.map { it.toUpperCase() }

println(UP)

}

The original “L” list and the transformed UP list are printed in the console to showcase the effect of the transformation as per the following attached image:

Example 3:

Let’s have our last illustration of this guide to demonstrate the functionality of the “map” filter function in the Kotlin programming. The code snippet utilizes the “map” functions in Kotlin to calculate the lengths of words in a given string and print the resulting list.

In the main function, the code begins by defining a string variable “str” with the “Welcome to Kotlin Programming” value. This string represents the sentence from which we want to calculate the word lengths. The “split” function is then applied to the “str” string. It takes a delimiter as an argument which, in this situation, is a space character ” “. The “split” function splits the string into individual words based on the provided delimiter and returns a list of words.

Next, the “map” function is applied to the resulting list of words. For each “it” element in the list, the lambda expression { it.length } calculates the length of each word using the length property. The length property yields the total number of characters in an original string. The “map” function collects all the word lengths and returns a new “L” list that contains the lengths of the words in the original string.

Finally, the “println” statement is used to print the “L” list which contains the lengths of the words from the original string. The output is [7, 2, 6, 11] which represents the lengths of the words “Welcome”, “to”, “Kotlin”, and “Programming”, respectively.

fun main() {

val str = "Welcome to Kotlin Programming"

val L = str.split(" ").map { it.length }

println(L)

}

The output for the provided code example splits a given string and then displays the calculated length of each word using the “map” function.

Conclusion

The aforementioned examples demonstrate the use and functioning of the “map” function in Kotlin. The examples illustrated numerous situations in which the “map” function was efficiently used. The lengths of the words in a sentence, the squares or cubes of the integers in a collection, and the conversion of a list of strings to uppercase are some of the few instances. In each scenario, the map function makes it easier to alter each member of the collection individually and then gather the results into a new collection.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.