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? 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
Merge Two Collections in Kotlin Kotlin is a statically typed, general-purpose programming language developed by JetBrains. The company famous for creating world-class IDEs like IntelliJ IDEA, PhpStorm, and AppCode. Kotlin was first introduced by JetBrains in 2011 and is designed to run on the Java Virtual Machine (JVM). It is an o
3 min read
Kotlin - Collection Operations Overview Kotlin provides a rich set of tools for working with collections like lists, sets, and maps. Whether you want to add, remove, sort, filter, or transform data, Kotlinâs standard library makes it easy and expressive.Two Ways Kotlin Defines Collection FunctionsCollection operations are declared in two
4 min read
Kotlin Collection Write operations In Kotlin, when we work with collections like lists or sets, sometimes we need to change or update their contents. If a collection allows us to modify its elements, we call it a MutableCollection. This means we can add, remove, or update its elements anytime. In this article, we will explore the dif
3 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
Kotlin list : listOf() In Kotlin, a List is a generic, ordered collection of elements. Lists are very common in everyday programming as they allow us to store multiple values in a single variable. Kotlin provides two types of lists - Immutable Lists (which cannot be changed and created using listOf()) and Mutable Lists (w
7 min read