Skip to main content
Logo image

Section 4.60 Optional: HashMap (Dictionary) Data Structure

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:

Activity 4.60.1.

Put more English and equivalent Spanish words into the dictionary.

Activity 4.60.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.
There is also a newer Java lambda operator that you can use to traverse through data collections. Try it above.
phoneBook.forEach((key, value) ->   
          System.out.println(key + " : " + value));
You have attempted of activities on this page.