Optional: HashMap (Dictionary) Data Structure

From CS Awesome 2CC BY-NC-SA 4.0Original page

Java1 class period2 exercises4 graded tests

Files

README.mdDownload

Optional: HashMap (Dictionary) Data Structure

Each coding exercise has its own folder. Open its .java file and press Run to try it. Run Tests checks every graded exercise in this lesson at once.

In this unit, we introduced the Java data structures of arrays, ArrayLists, and 2D arrays. In addition to these, Java provides many other data collection classes in the java.util library that are not covered in the AP CSA exam. This section provides an optional introduction to a powerful data structure called HashMap which stores key-value pairs. In a HashMap, each key is unique and serves as an index that maps to a specific value. Other programming languages like Python call this data structure a dictionary. For example, given a word (the key) you can look up its definition (the value) in a dictionary.

Here is how you use a HashMap in Java to create an English-Spanish dictionary:

import java.util.*;

HashMap<String, String> dictionary = new HashMap<String, String>();
dictionary.put("cat","gato");
String spanish = dictionary.get("cat");
System.out.println("The Spanish word for cat is " + spanish);

In this example, we create a HashMap called dictionary that maps English words (the keys) to their Spanish translations (the values). We add a key-value pair using the put method and retrieve the value using the get method. To check if a key exists in the HashMap, you can use the containsKey method.

We can loop through the keys and values in the HashMap using a for-each loop. Here is an example:

for (String key : dictionary.keySet())
{
    String value = dictionary.get(key);
    System.out.println(key + " in Spanish is " + value);
}

Let's try this code out below.

Exercise 1

Put more English and equivalent Spanish words into the dictionary.

Open the 01-dictionaryPut folder and edit EnglishSpanishDictionary.java. Press Run to try it; Run Tests checks it (1 test).

Exercise 2

Can you create a HashMap that maps the names of your friends to their phone numbers? Print out the name and phone number of each friend.

Open the 02-HashMapPhoneBook folder and edit FriendsPhoneBook.java. Press Run to try it; Run Tests checks it (3 tests). Its tests check your code, not what it prints: “Code contains phoneBook.put”, “Code contains phoneBook.get”, “Code contains for”.

More practice

There is also a newer Java lambda operator that you can use to traverse through data collections. Try it in 02-HashMapPhoneBook, though its tests still look for phoneBook.get and a for loop.

phoneBook.forEach((key, value) ->
          System.out.println(key + " : " + value));

For teachers

Optional: HashMap (Dictionary) Data Structure

Students read CSAwesome2's “Optional: HashMap (Dictionary) Data Structure” in CS Room and work through its 2 Java coding exercises.

  • Time: 1 class period
  • Tests: 4 in 2 graded exercises, set up for you when you import the lesson

Goals

  • Practice for Unit 4: Data Collections.

Before class

In class

  1. Students read README.md.
  2. Students do exercises 01–02, each in its own folder, pressing Run to try their code.
  3. Run Tests checks every graded exercise at once; scores appear in the Gradebook. Grading uses your copy of the tests, so a student who edits theirs does not change the grade.

Exercises

FolderFileGradingTests
01-dictionaryPutEnglishSpanishDictionary.javaAutograded1
02-HashMapPhoneBookFriendsPhoneBook.javaChecks code text only3

Teachers can download a reference solution after signing in.