Activity 4.60.1.
Put more English and equivalent Spanish words into the dictionary.
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.
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);
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.
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);
}
lambda operator
that you can use to traverse through data collections. Try it above.
phoneBook.forEach((key, value) ->
System.out.println(key + " : " + value));