What a dictionary is
A dictionary stores key-value pairs. You look something up by its key and get back the value stored with it, the way you find a phone number by looking up a name. Other languages give this structure its own syntax. In Java it is a class from the standard library, and the most common one is HashMap.
Use a HashMap whenever you need to find a value by a label instead of by position: scores by student name, prices by product code, counts by word. Each key appears at most once, while different keys may hold equal values.
Creating a HashMap
The class lives in the java.util package, so a full program starts with import java.util.HashMap; (or import java.util.*;). Then you declare the map and create it with new:
HashMap<String, Integer> scores = new HashMap<>();
Read it from the left:
HashMap<String, Integer>is the type. The two names in angle brackets are the key type and the value type, so this map usesStringkeys andIntegervalues.scoresis the variable name.new HashMap<>()creates an empty map. The empty angle brackets are called the diamond. Java fills in the types from the declaration on the left, so you don't have to write them twice.
The type arguments must be object types, which is why the value type is Integer and not int. Integer is the wrapper class for int. Java converts between the two automatically, so you can write put("Alice", 95) with a plain number. The other wrappers follow the same pattern: Double, Boolean and Character.
Adding entries with put
The put(key, value) method adds an entry:
HashMap<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
System.out.println(ages.get("Alice")); // 25
System.out.println(ages.size()); // 2
get(key) returns the value for a key, and size() returns the number of entries. If you call put with a key that is already in the map, the old value is replaced instead of a second entry being added. So the map never holds two entries with the same key.
The lesson's exercise
The task is to build a map named scores with three students. It has two steps:
- Create the map. Declare
scoresas aHashMap<String, Integer>and initialize it withnew HashMap<>(). The map starts empty. - Add the three entries. Call
putonce per student:"Alice"with 95,"Bob"with 87 and"Charlie"with 72.
The complete code is:
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Charlie", 72);
Afterwards the map holds three entries, and scores.get("Bob") is 87.
Good to know
- The order is not guaranteed. A
HashMapdoesn't remember the order you inserted entries in, and printing it or looping over its keys can list them in an order that looks random. Never rely on that order. If you need insertion order, useLinkedHashMap, and for keys in sorted order,TreeMap. - Keys are compared with
equals."Alice"and"alice"are different keys, so the capitalization you use inputmust match later inget. - Keys can be other types. A
HashMap<Integer, String>maps numbers to text: afterbyId.put(7, "Ann"),byId.get(7)gives"Ann". - Declaring with the interface is common.
Map<String, Integer> scores = new HashMap<>();works the same way for the methods in this chapter and lets you swap the implementation later. This lesson usesHashMapas the declared type. - Forgetting the import is a compile error. Without
java.util.HashMapimported, the compiler reports that it cannot find the symbolHashMap.
Key takeaways
- A
HashMap<K, V>stores unique keys of typeK, each with a value of typeV. - Create one with
new HashMap<>()and fill it withput(key, value). - The type arguments must be object types, such as
Integerinstead ofint. - A repeated key replaces the old value, and the iteration order is unspecified.