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
Working with Anonymous Function in Kotlin
In Kotlin, we can have functions as expressions by creating lambdas. Lambdas are function literals that is, they are not declared as they are expressions and can be passed as parameters. However, we cannot declare return types in lambdas. Although the return type is inferred automatically by the Kot
3 min read
How to Write swap Function in Kotlin using the also Function?
also is an extension function to Template class which takes a lambda as a parameter, applies contract on it, executes the lambda function within the scope of calling object, and ultimately returns the same calling object of Template class itself. Swapping two numbers is one of the most common things
3 min read
Kotlin | Collection Transformation
Kotlin standard library provides different set of extension functions for collection transformations. These functions help in building new collections from existing collections based on the rules defined by the transformation. There are different number of transformation functions: MappingZippingAss
5 min read
Sort a List by Specified Comparator in Kotlin
As we all know Sorting a list is one of the most common operations done on the list so, in this article, we are going to discuss how to sort a list by the specified comparator in Kotlin. When we try to sort a list of custom objects, we need to specify the comparator. Let's see how we can sort a list
3 min read
Kotlin | Plus and minus Operators
In Kotlin, plus and minus operators are used to work with the list of objects which is usually referred to as Collections (List, Set, Maps). As the name suggests, plus operator adds up or concatenates the elements or objects of the given collections. The elements of the first collection remains as i
2 min read
How to Pass a Function as a Parameter to Another in Kotlin?
Kotlin gives us the power to declare high-order functions. In a high-order function, we can pass and return functions as parameters. This is an extremely useful feature and makes our code much easier to work with. In fact, many of the Kotlin library's functions are high order, such as NBQ. In Kotlin
4 min read
Kotlin Collection Write operations
Collection Write operations are used to change the content of MutableCollection. MutableCollection is defined as the Collection with write operations like add and remove. Operations supported are as follows: Adding elements Removing elements and Updating elements Addition of elements - add() functio
4 min read
Kotlin - Collection Operations Overview
The Kotlin standard library provides a wide range of functions for performing operations on collections. It includes simple operations like getting or adding elements and also includes more complex ones like searching, sorting, filtering, etc. Member and Extension functions - Collection operations a
4 min read
Kotlin Collections Ordering
There are certain collections where the order of the elements is important. If you take lists, two lists are never equal if they are ordered differently inspite of having same elements.In Kotlin, there are different ways of ordering the elements. Most built-in types are comparable: -Numeric types fo
4 min read
Kotlin | Retrieve Collection Parts
The slice function allows you to extract a list of elements from a collection by specifying the indices of the elements you want to retrieve. The resulting list contains only the elements at the specified indices. The subList function allows you to retrieve a sublist of a collection by specifying th
5 min read