Learn
Loops
Iterating Through Maps

Unlike a list or a set, a map is a collection of entries. When using a map as a for loop iterator, we can iterate through each entry of the map or through just the keys, or just the values.

When iterating through a map, the loop variable will hold one entry per iteration. The entry’s key and value can be accessed using the properties, key and value:

val myClothes = mapOf("Shirts" to 7, "Pairs of Pants" to 4, "Jackets" to 2) for (itemEntry in myClothes) { println("I have ${itemEntry.value} ${itemEntry.key}") }

Notice that in order to access the attributes in a String template, we surround the loop variable and the attribute in curly brackets.

We can also access the key and value of each entry by destructuring using two loop variables in parentheses. The first variable is the entry’s key and the second is the value:

val myClothes = mapOf("Shirts" to 7, "Pairs of Pants" to 4, "Jackets" to 2) for ((itemName, itemCount) in myClothes) { println("I have $itemCount $itemName") }

Both examples have the same output:

I have 7 Shirts I have 4 Pairs of Pants I have 2 Jackets

Lastly, we can iterate through just a map’s keys or values. A map has the properties keys and values which can each be used as an iterator:

val myClothes = mapOf("Shirts" to 7, "Pairs of Pants" to 4, "Jackets" to 2) println("KEYS") for (itemName in myClothes.keys) { println(itemName) } println("\nVALUES") for (itemCount in myClothes.values) { println(itemCount) }

Here is the output:

KEYS Shirts Pairs of Pants Jackets VALUES 7 4 2

Instructions

1.

The map favoriteColors holds the names of people and their favorite colors. The keys of the map are the people’s names and the values of the map are their favorite colors. Start by iterating through the map favoriteColors to access each entry and output its key and value.

Implement a for loop that contains:

  • favoriteEntry as the loop variable
  • favoriteColors as the iterator
  • a println() statement in the loop body that outputs the key and value of each entry separated by a colon. Example output, Jesse: Violet

Be sure to use curly brackets in the string template when accessing the attributes of the entry in the loop variable.

2.

Nice work. Now you’re going to create a loop that iterates through just the map’s values.

Create another for loop that contains:

  • color as the loop variable
  • the values attribute of favoriteColors as the iterator.
  • a println() statement in the loop body that outputs the value of each entry.
Folder Icon

Take this course for free

Already have an account?