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 Collection Transformation The Kotlin Standard Library provides a rich set of extension functions for transforming collections. These transformations help us to build new collections or values derived from existing collections based on specific transformation logic. Kotlin supports several types of collection transformations,
5 min read
Sort a List by Specified Comparator in Kotlin Sorting a list is one of the most common operations we perform when working with collections. In this article, weâll learn how to sort a list by a specified comparator in Kotlin especially when the list contains objects of a custom class.Kotlin ComparatorIn Kotlin, a Comparator is an interface that
3 min read
Passing Variable Arguments to a Function in Kotlin There are a lot of scenarios in which we need to pass variable arguments to a function. In Kotlin, You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. a vararg parameter of type T is internally represented as an array of type T ( Array<T
4 min read
Kotlin | Plus and minus Operators In Kotlin, working with collections like lists, sets, and maps is made easier and more readable thanks to operators like + (plus) and â (minus). These operators help you combine or remove elements from collections in a very natural way, just like doing math, but with objects instead of numbers.Worki
2 min read
How to Pass a Function as a Parameter to Another in Kotlin? In Kotlin, we have the amazing power to work with higher-order functions. These are special kinds of functions that can take other functions as parameters or even return functions as results. This feature makes our code more flexible, cleaner, and easier to understand. In fact, many useful functions
3 min read