๐ŸŽ“ A1Learner
๐Ÿ”

Kotlin Maps

A map is a collection that pairs each key with a value. A key finds its paired value with one lookup.

A whole map printed

The map pairs two names with scores. Printing it shows each pair with an equals sign.

fun main() {
    val scores = mapOf("Ana" to 90, "Bo" to 75)
    println(scores)
}

A value found by its key

The key Ana sits in square brackets. The lookup prints the score paired with Ana.

fun main() {
    val scores = mapOf("Ana" to 90, "Bo" to 75)
    println(scores["Ana"])
}

A lookup that finds nothing

The map has no key named Cy. The lookup prints null because there is no paired value.

fun main() {
    val scores = mapOf("Ana" to 90, "Bo" to 75)
    println(scores["Cy"])
}

One line for each pair

The for loop takes each pair apart into a name and a score. Each visit prints one line.

fun main() {
    val scores = mapOf("Ana" to 90, "Bo" to 75)
    for ((name, score) in scores) {
        println("$name scored $score")
    }
}

Example

fun main() {
    val scores = mapOf("Ana" to 90, "Bo" to 75, "Cy" to 82)
    println(scores.size)
    println(scores["Bo"])
    println(scores["Dee"])
}

Key points

  • mapOf: the call that builds a map from pairs.
  • to: the word that joins a key to its value in a pair.
  • Use a key in square brackets to look up its value.
  • A lookup for a missing key gives null.
  • size: the .size value counts the pairs in a map.

In this example, the map holds three pairs, so size prints 3. The key Bo prints its paired score 75. The key Dee is missing, so its lookup prints null.

Note

A map prints its pairs in the order they were written.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What does scores["Ana"] give for the map mapOf("Ana" to 90, "Bo" to 75)?