Transform a List Using Map Function in Kotlin
Last Updated :
21 Jun, 2022
Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a “better language” than Java, but still be fully interoperable with Java code. In this article, we will learn how to transform a list using a map function in Kotlin, and how to filter the list with whichever criteria we like. We will be using lambda functions, which provide a great way to do functional programming. So let's get started.
Example
First, let's see how to use the filter function on a list. The filter function returns a list containing all elements matching the given predicate. We will create a list of numbers and filter the list based on even or odd. The filter method is good for an immutable collection as it doesn't modify the original collection but returns a new one. In the filter method, we need to implement the predicate. The predicate, like the condition, is based on the list that is filtered. For example, we know that even items will follow it%2==0. So the corresponding filter method will look like this:
Kotlin
val listOfNumbers = listOf (1, 2, 3, 4, 5, 6, 7, 8, 9)
var evenList = listOfNumbers.filter {
it %2==0
}
println (evenList)
Output:
[2, 4, 6, 8]
Another variant of the filter function is filterNot, which, as the name suggests, returns a list containing all elements not matching the given predicate. Another cool lambda function is the map. It transforms the list and returns a new one:
Kotlin
val listOfNumbers = listOf (1, 2, 3, 4, 5, 6, 7, 8, 9)
var transformedList = listOfNumbers.map {
it*2
}
println(transformedList)
Output:
[2, 4, 6, 8, 10, 12, 14, 16, 18]
A variant of the map function is map Indexed. It provides the index along with the item in its construct:
Kotlin
val listOfNumbers=listOf (1, 2, 3, 4, 5)
val map=listOfNumbers.mapIndexed { index, it
-> it*index
}
println(map)
Output:
[0, 2, 6, 12, 20]
Transforming Maps
Like other collection types in Kotlin, there are many ways of transforming maps for the needs of our application. Let’s look at a few useful operations. For all the examples shown below, this is the initial data in our inventory map:
val inventory = mutableMapOf(
"Vanilla" to 54,
"Chocolate" to 64,
"Strawberry" to 39,
)
Kotlin provides several filter methods for maps. To filter by the enter key or value, there are filterKeys and filterValues, respectively. If we need to filter by both, there is the filter method. Here’s an example of filtering our ice cream inventory by the amount left:
val lotsLeft = inventory.filterValues { qty -> qty > 10 }
assertEquals(setOf("Vanilla", "Chocolate"), lotsLeft.keys)
- The filterValues method applies the given predicate function to every entry’s value in the map. The filtered map is the collection of entries that match the predicate condition.
- If we wanted to filter out entries that didn’t match this condition, we could’ve used the filterNot method instead.
Which One to Use?
If both methods essentially achieve the same functionality, which one should we use? toMap, in terms of implementation, is more intuitive. However using this method requires us to transform our Array into Pairs first, which later have to be translated to our Map, so this operation will be particularly useful if we’re already operating on collections of Pairs.
Similar Reads
Kotlin Tutorial This Kotlin tutorial is designed for beginners as well as professional, which covers basic and advanced concepts of Kotlin programming language. In this Kotlin tutorial, you'll learn various important Kotlin topics, including data types, control flow, functions, object-oriented programming, collecti
4 min read
Kotlin Android Tutorial Kotlin is a cross-platform programming language that may be used as an alternative to Java for Android App Development. Kotlin is an easy language so that you can create powerful applications immediately. Kotlin is much simpler for beginners to try as compared to Java, and this Kotlin Android Tutori
6 min read
Retrofit with Kotlin Coroutine in Android Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit library is popular among the developers to use the API key. The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can e
3 min read
Introduction to Kotlin Kotlin is a statically typed, general-purpose programming language developed by JetBrains, which has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 as a new language for the JVM. Kotlin is an object-oriented language, and a better lang
4 min read
Kotlin Data Types The most fundamental data type in Kotlin is the Primitive data type and all others are reference types like array and string. Java needs to use wrappers (java.lang.Integer) for primitive data types to behave like objects but Kotlin already has all data types as objects.There are different data types
3 min read
Kotlin when expression In Kotlin, when replaces the switch operator of other languages like Java. A certain block of code needs to be executed when some condition is fulfilled. The argument of when expression compares with all the branches one by one until some match is found. After the first match is found, it reaches to
6 min read
Kotlin Constructor A constructor is a special member function that is automatically called when an object of a class is created. Its main purpose is to initialize properties or perform setup operations. In Kotlin, constructors are concise, expressive, and provide significant flexibility with features like default para
6 min read
Android RecyclerView in Kotlin In this article, you will know how to implement RecyclerView in Android using Kotlin . Before moving further let us know about RecyclerView. A RecyclerView is an advanced version of ListView with improved performance. When you have a long list of items to show you can use RecyclerView. It has the ab
4 min read
ProgressBar in Android Progress Bar are used as loading indicators in android applications. These are generally used when the application is loading the data from the server or database. There are different types of progress bars used within the android application as loading indicators. In this article, we will take a lo
3 min read
Kotlin Array An Array is one of the most fundamental data structures in practically all programming languages. The idea behind an array is to store multiple items of the same data type, such as an integer or string, under a single variable name. Arrays are used to organize data in programming so that a related s
6 min read