Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Looping over Map objects

Imagine we have a Map<String, Double> that maps city names to their populations (in millions, from 2017 via Google via this source). We could imagine the following values being added to our Map

Map<String, Double> populations = new TreeMap<String, Double>();
populations.put("Seattle", 0.724);
populations.put("Los Angeles", 4.0);
populations.put("New York", 8.623);
populations.put("Chicago", 2.716);
populations.put("Philadelphia", 1.581);

We could print out our Map using a call to its toString() method, which would give us the following result:

System.out.println(populations);
// Output: {Chicago=2.716, Los Angeles=4.0, New York=8.623, Philadelphia=1.581, Seattle=0.724}

But what if we wanted to do something with the values in our Map such as printing them out in a different format, or finding the city with the highest population? For these tasks, we need to know how to loop over the items in our Map.

Printing in a better format

Say I want to print out the items in my Map in the following format

*city* has a population of *population* million 

How would we go about doing this? Well we need a way to somehow get access to the keys and values of our Map. Perhaps you recall seeing the methods values() and keySet() on the lecture slides about the Map interface. A call to values() returns all the values in our current Map. A call to keySet() returns all of the keys in our current Map. Since we know we want to print out the populations, why don't we start by looping through all of the values in the Map

for (double population : populations.values()) {
    // Do something
}

So now we have access to the values in our Map (the populations), but in order to print in the format mentioned above we also need access to the keys in our Map (cities associated to those populations). We could try the following:

for (double population : populations.values()) {
    for (String city : populations.keySet()) {
        if (populations.get(city) == population) {
            System.out.println(city + " has a population of " + population + " million");
        }
    }
}

This works, but it seems a bit clunky and very inefficient (it has a complexity of Big O(n^2) where n is the number of key-value pairs in the Map, since we loop over all the values and then for each value we loop over all the keys). In order to find the correct key/value pair we have to loop over the keys and get the values associated with them anyhow. Remember, in Map objects we go from the key to the value. We don't have an easy way to get from the value to the key. So rather than looping over the values in our Map and then trying to somehow access the keys, it would be much easier to more appropriately use the design of Map objects and initially loop over the keys. Let's try solving the problem again, this time initially looping over the keySet()

for (String city : populations.keySet()) {
    double population = populations.get(city);
    System.out.println(city + " has a population of " + population + " million");
}

Wow that looks so much better! It's also important to note that our second solution is much more efficient than our first solution was (our updated solution has Big O(n) since it just loops over the keys). Use this exercise as a reminder that when we loop over Map objects, we should always go from the key to the value. Below is a skeleton outline of how to loop over Map objects, though the details may change depending on the task at hand

for (KeyType key : mapName.keySet()) {
    ValueType value = mapName.get(key);
    // Do something with key and/or value
}

More Practice with Map objects

Try this problem for a bit of practice with building Map objects.


Have any feedback about this reading? Please let us know using this form.

Copyright © 2019 Hunter Schafer and Porter Jones. All rights reserved. Permission is hereby granted to students registered for University of Washington CSE 143 for use solely during Winter Quarter 2019 for purposes of the course. No other use, copying, distribution, or modification is permitted without prior written consent. Copyrights for third-party components of this work must be honored. Instructors interested in reusing these course materials should contact the authors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.