Ebooks

Kotlin maps

Kotlin maps tutorial shows how to work with maps in Kotlin. A map is a collection of pairs of objects.

Kotlin distinguishes between read-only and mutable maps. Read-only maps are created with mapOf() and mutable maps with mutableMapOf().

Kotlin map

A map is a collection that holds pairs of objects. Each pair consists of a key and a value. Map keys are unique; the map holds only one value for each key.

Kotlin mapOf()

The mapOf() method creates a read-only map with the specified contents, given as a list of pairs where the first value is the key and the second is the value.

KotlinMapOf.kt
package com.zetcode

fun main() {

    val chars = mapOf(97 to "a", 98 to "b", 120 to "x")
    println(chars)

    val user = mapOf("name" to "Luke", "age" to "23")
    println(user)
}

The example creates two maps.

{97=a, 98=b, 120=x}
{name=Luke, age=23}

This is the output.

Kotlin HashMap

A map can be created from Java's HashMap.

KotlinHashMap.kt
package com.zetcode

fun main() {

    val items = HashMap<String, Int>()

    items["A"] = 90
    items["B"] = 80
    items["C"] = 70

    for ((k, v) in items) {
        println("$k = $v")
    }
}

The example creates a map using Java's HashMap and prints the values and pairs to the console.

Kotlin map size

The size of a map (the number of pairs) can be determined with the size property and the count() method.

KotlinMapSize.kt
package com.zetcode

fun main() {

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)

    println("Map has ${items.size} items")
    println("Map has ${items.count()} items")

    val n = items.count { it.value > 10 }
    println("# of values greater that 10: $n")
}

The example counts the number of map pairs.

val n = items.count { it.value > 10 }

With the count() method we count the number of values that are greater than ten.

Map has 4 items
Map has 4 items
# of values greater that 10: 3

This is the output.

Kotlin entries, keys, values

A Kotlin map has properties to get all entries, keys, and values.

KotlinEntriesKeysValues.kt
package com.zetcode

fun main() {

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33)

    println("Entries: " + items.entries)
    println("Keys:" + items.keys)
    println("Values:" + items.values)
}

The example uses the entries, keys, and values properties.

Entries: [coins=12, books=45, cups=33]
Keys:[coins, books, cups]
Values:[12, 45, 33]

This is the output.

Kotlin mutableMapOf

A mutable map is created with mutableMapOf().

KotlinMutableMap.kt
package com.zetcode

fun main() {

    val user = mutableMapOf("name" to "John Doe", "occupation" to "programmer")
    println(user)

//    user.put("location", "USA")
    user["location"] = "USA"
    println(user)

    user.remove("occupation")
    println(user)

    user.clear()
    println(user)

    if (user.isEmpty()) {
        println("empty")
    } else {
        println("not empty")
    }
}

The example creates a mutable map and presents of its methods.

//    user.put("location", "USA")
user["location"] = "USA"
println(user)

A new pair is added to the map. IntelliJ IDEA recommends the assignment operation.

user.remove("occupation")

A pair is deleted with remove().

user.clear()

All pairs are removed with clear().

if (user.isEmpty()) {
    println("empty")
} else {
    println("not empty")
}

The isEmpty() method checks if the map is empty.

{name=John Doe, occupation=programmer}
{name=John Doe, occupation=programmer, location=USA}
{name=John Doe, location=USA}
{}
empty

This is the output.

Kotlin get values

There are several method to retrieve values from a Kotlin map.

KotlinMapGet.kt
package com.zetcode

fun main() {

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)

//    println(items.get("coins"))
    println(items["coins"])

    println(items.getValue("coins"))

    println(items.getOrDefault("pens", 0))
    println(items.getOrDefault("pencils", 0))

    val nOfPencils = items.getOrElse("pencils", {
        0
    })

    println(nOfPencils)
}

The example gets values from a map.

//    println(items.get("coins"))
println(items["coins"])

IntelliJ IDEA recommends to use the indexing operation instead of get().

println(items.getOrDefault("pens", 0))

The getOrDefault() returns the value corresponding to the key or the specified default value if the key is not present.

val nOfPencils = items.getOrElse("pencils", {
    0
})

The getOrElse() returns the value for the given key, or the result of the specified function if there was no entry for the given key.

Kotlin contains key/value

The containsKey() checks if the map contains a key. The containsValue() checks if the map contains a value.

KotlinMapContains.kt
package com.zetcode

fun main() {

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)

    if (items.containsKey("cups")) {

        println("contains cups")
    } else {

        println("does not contain cups")
    }

    val value = 25

    if (items.containsValue(value)) {

        println("contains value $value")
    } else {

        println("does not contain value $value")
    }
}

The example checks if the map contains key "cups" and value 25.

Kotlin map forEach

With forEach(), we can traverse the map.

KotlinMapForEach.kt
package com.zetcode

fun main() {

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)

    items.forEach { (k, v) -> println("There are $v $k") }
}

The example goes through the map with forEach().

There are 12 coins
There are 45 books
There are 33 cups
There are 2 pens

This is the output.

Kotlin filter map

We can filter maps with filterKeys(), filterValues(), and filter().

KotlinMapFilter.kt
package com.zetcode

fun main() {

    val items = mapOf("A" to 90, "B" to 80, "C" to 70, "D" to 60, "E" to 50)

    val filtered = items.filterKeys { it == "A" || it == "C" }
    println(filtered)

    val filtered2 = items.filterValues { it >= 70 }
    println(filtered2)

    val filtered3 = items.filter { it.key == "A" || it.value == 50 }
    println(filtered3)
}

The example filters a map.

val filtered = items.filterKeys { it == "A" || it == "C" }

We filter out all pairs that match the specified keys.

val filtered2 = items.filterValues { it >= 70 }

We filter out all pairs that match the specified values.

val filtered3 = items.filter { it.key == "A" || it.value == 50 }

Here we filter out all pairs that match the given key or value.

{A=90, C=70}
{A=90, B=80, C=70}
{A=90, E=50}

This is the output.

Kotlin sorted map

A sorted map is created with sortedMapOf().

KotlinSortedMap.kt
package com.zetcode

fun main() {

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)
    println(items)

    val sortedItems = sortedMapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)
    println(sortedItems)
}

The example prints an unsorted and sorted map.

{coins=12, books=45, cups=33, pens=2}
{books=45, coins=12, cups=33, pens=2}

The pairs are sorted by keys.

Kotlin map any

The any() method returns true if at least one entry matches the given predicate.

KotlinMapAny.kt
package com.zetcode

fun main() {

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33, "pens" to 2)

    val value = 12

    val hasValue = items.any { it.value == value }

    if (hasValue) {
        println("The map has value $value")
    } else {
        println("The map does not have value $value")
    }

    val isEven: (Int) -> Boolean = { it % 2 == 0 }

    val hasEvenValue = items.any { isEven(it.value) }

    if (hasEvenValue) {
        println("The map has even value(s)")
    } else {
        println("The map does not have even value(s)")
    }
}

In the example, we check if the map contains at least one value 12 and if there is at least one even value.

The map has value 12
The map has even value(s)

This is the output.

In this tutorial, we have covered Kotlin maps. You might also be interested in the related Kotlin tutorials: Kotlin sets tutorial, Kotlin arrays tutorial, or list all Kotlin tutorials.