As we’ve seen with other collection types in Kotlin, we are able to retrieve and access the contents of a collection with the help of built-in functions and other tools. With the map collection, we are able to retrieve a value using the shorthand
Assume the following example that holds famous band names as keys and lead singers as values:
var leadSingers = mapOf("The Rolling Stones" to "Mick Jagger", "Blondie" to "Debbie Harry", "Queen" to "Freddie Mercury")
We can access any value by wrapping its key in square brackets:
leadSingers["Blondie"] // Debbie Harry
If we’re building an application that will display the names of the bands at the top of the page, we can gather all keys at once using the
leadSingers.keys // [The Rolling Stones, Blondie, Queen]
Similarly, a set of all map values can be returned using the
leadSingers.values // [Mick Jagger, Debbie Harry, Freddie Mercury]
Each expression can be wrapped in a print statement to see its output or stored in a variable for later use.
In Transportation.kt, we’ve declared a map containing various forms of unique transportation in different countries. Retrieve a transportation mode that exists in Peru and wrap it in a print statement using a String template:
"A unique mode of transportation that exists in Peru is mapName[key]."
Make sure to replace the placeholders,
key, with the correct names.
On the following line, output all keys from the
uniqueTransport map using a single property. Wrap this code in a
Next, output all values from the map using a single property. Wrap this code in a
println() statement as well.