# 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:

```java
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:

```java
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.

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