How to Work With Collections (Lists, Maps, Etc.) In Kotlin?

11 minutes read

To work with collections in Kotlin, you can use various data structures such as lists, maps, sets, and arrays. These collections provide different ways to store and manipulate groups of elements. Here's an overview of how to work with collections in Kotlin:


Lists:

  • A list is an ordered collection of elements. You can define a list by using the listOf() function or the mutableListOf() function (if you need to modify the list).
  • Example: val numbers = listOf(1, 2, 3, 4, 5) val mutableList = mutableListOf("apple", "banana", "orange")
  • You can access elements in a list using the indexing operator []. Lists are read-only by default, so you cannot modify their elements.
  • Example: val firstElement = numbers[0]


Maps:

  • A map is a collection that holds key-value pairs. Each element in the map is unique and is identified by its key.
  • You can define a map using the mapOf() function or the mutableMapOf() function (if you need to modify the map).
  • Example: val map = mapOf("name" to "John", "age" to 25) val mutableMap = mutableMapOf("apple" to 1, "banana" to 2, "orange" to 3)
  • You can access values in a map by providing the key inside square brackets []. Like lists, maps are read-only by default.
  • Example: val name = map["name"]


Sets:

  • A set is an unordered collection of unique elements. It does not allow duplicate values.
  • You can define a set using the setOf() function or the mutableSetOf() function (if you need to modify the set).
  • Example: val set = setOf(1, 2, 3, 4, 5) val mutableSet = mutableSetOf("apple", "banana", "orange")
  • You can perform set operations like union, intersection, and difference using built-in set functions.


Arrays:

  • Arrays are fixed-size collections of elements that allow random access.
  • You can define an array using the arrayOf() function or the Array constructor.
  • Example: val array = arrayOf(1, 2, 3, 4, 5)
  • You can access elements in an array using the indexing operator []. Arrays have a fixed size and cannot be expanded.


These are the basic ways to work with collections in Kotlin. Kotlin provides many functions and extensions for manipulating, filtering, and transforming collections, making it easier to work with complex data structures.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin

Rating is 4.9 out of 5

Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin

3
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Rating is 4.8 out of 5

Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

4
Kotlin in Action

Rating is 4.7 out of 5

Kotlin in Action

5
Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

Rating is 4.6 out of 5

Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

6
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.5 out of 5

Head First Kotlin: A Brain-Friendly Guide

7
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.4 out of 5

Kotlin Cookbook: A Problem-Focused Approach

8
How to Build Android Apps with Kotlin: A practical guide to developing, testing, and publishing your first Android apps, 2nd Edition

Rating is 4.3 out of 5

How to Build Android Apps with Kotlin: A practical guide to developing, testing, and publishing your first Android apps, 2nd Edition

9
Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

Rating is 4.2 out of 5

Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

10
Java to Kotlin: A Refactoring Guidebook

Rating is 4.1 out of 5

Java to Kotlin: A Refactoring Guidebook


How to access the value of a specific key in a map in Kotlin?

To access the value of a specific key in a map in Kotlin, you can use the get() function or the indexing operator [] on the map object. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
fun main() {
    val map = mapOf("key1" to "value1", "key2" to "value2", "key3" to "value3")

    // Using get() function
    val value1 = map.get("key1")
    println(value1) // Output: value1

    // Using indexing operator
    val value2 = map["key2"]
    println(value2) // Output: value2
}


In the above code, the map variable stores a map where string keys are associated with string values. The get("key1") returns the value associated with the key "key1" ("value1"), and map["key2"] returns the value associated with the key "key2" ("value2"). The values are then printed to the console.


How to transform a list using a mapping function in Kotlin?

To transform a list using a mapping function in Kotlin, you can use the map function. Here's an example:

1
2
3
4
5
val numbers = listOf(1, 2, 3, 4, 5)

val multipliedNumbers = numbers.map { it * 2 }

println(multipliedNumbers) // Output: [2, 4, 6, 8, 10]


In the above example, the map function is applied to each element of the numbers list, multiplying each element by 2 and creating a new list multipliedNumbers with the transformed values.


You can also use a named function as the mapping function. Here's an example:

1
2
3
4
5
6
7
8
9
fun multiplyByTwo(number: Int): Int {
    return number * 2
}

val numbers = listOf(1, 2, 3, 4, 5)

val multipliedNumbers = numbers.map(::multiplyByTwo)

println(multipliedNumbers) // Output: [2, 4, 6, 8, 10]


In this example, the multiplyByTwo function is defined separately, and ::multiplyByTwo is passed as the mapping function to map.


How to convert a list to a map in Kotlin?

To convert a list to a map in Kotlin, you can use the associateBy function. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
data class Person(val id: Int, val name: String)

fun main() {
    val persons = listOf(
        Person(1, "Alice"),
        Person(2, "Bob"),
        Person(3, "Charlie")
    )

    val map = persons.associateBy { it.id }
    println(map)
}


In this example, we have a Person data class with an id property. We have a list of Person objects, and we want to convert it into a map where the key is the id and the value is the Person object itself.


The associateBy function takes a lambda expression that defines the key for each element in the list. In this case, we use { it.id } as the lambda expression to extract the id property as the key.


The result will be a map with the following content:

1
{1=Person(id=1, name=Alice), 2=Person(id=2, name=Bob), 3=Person(id=3, name=Charlie)}


Note that if the list contains duplicate keys, the associateBy function will throw an exception.


How to perform a custom operation on each key-value pair of a map in Kotlin?

In Kotlin, you can perform a custom operation on each key-value pair of a map using the map extension function. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
val map = mapOf("key1" to "value1", "key2" to "value2", "key3" to "value3")

val modifiedMap = map.map { (key, value) ->
    // Perform your custom operation here
    // For example, let's add "Modified" suffix to each value
    key to "$value Modified"
}

// Print the modified map
modifiedMap.forEach { (key, value) ->
    println("$key -> $value")
}


Output:

1
2
3
key1 -> value1 Modified
key2 -> value2 Modified
key3 -> value3 Modified


In the map function, we iterate over each key-value pair using destructuring declaration (key, value). You can perform any custom operation on the key and value variables as required. The result of the custom operation is then assigned to a new key-value pair in the modifiedMap.


Finally, you can iterate over the modifiedMap using forEach to print or use each modified key-value pair.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

Working with collections in Dart, such as lists, maps, and sets, allows you to efficiently manage and manipulate groups of related data. These data structures provide different ways to store, access, and modify data.Lists: A list in Dart represents an ordered ...
In Haskell, lists are a fundamental data structure used to store sequences of elements of the same type. The elements of a list are enclosed within square brackets and separated by commas. Lists are immutable, meaning once created, their elements cannot be mod...
To find the intersection of multiple lists in Kotlin, you can use the intersect method provided by the standard library. This method takes two or more lists as arguments and returns a new list containing only the elements that are common to all input lists. Yo...