Sub topic 12
Key-Value Lookup with Map and HashMap
What a Map Is
A Map is a collection that stores pairs. Each pair has a key and a value. The key is what you look up. The value is what you get back.
A phone book works this way. You look up a name (the key) and find a number (the value).
A Map has two simple rules:
- Each key appears only once. If you add the same key again, the new value replaces the old one.
- Values can repeat. Two different keys can have the same value.
Map is an interface. HashMap is the most common class that implements it. A HashMap finds a key very quickly, even when it holds thousands of entries. It does not keep keys in any particular order.
Declaring a HashMap
A Map needs two type parameters: one for the key type and one for the value type.
import java.util.HashMap;
import java.util.Map;
public class MapBasics {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Ana", 30);
ages.put("Ben", 25);
ages.put("Ana", 31); // replaces 30
System.out.println(ages.get("Ana")); // 31
System.out.println(ages.get("Zoe")); // null
System.out.println(ages.size()); // 2
ages.remove("Ben");
System.out.println(ages.containsKey("Ben")); // false
}
}Here is what each method does:
| Method | What it does |
|---|---|
| `put(key, value)` | Adds a pair, or replaces the value if the key exists |
| `get(key)` | Returns the value, or `null` if the key is missing |
| `containsKey(key)` | Returns `true` if the key is in the map |
| `remove(key)` | Deletes the pair with that key |
| `size()` | Returns the number of pairs |
Counting with getOrDefault and merge
Counting things is a very common job for a map. Here is a word counter.
import java.util.HashMap;
import java.util.Map;
public class WordCount {
public static void main(String[] args) {
String[] words = {"to", "be", "or", "not", "to", "be"};
Map<String, Integer> counts = new HashMap<>();
for (String w : words) {
counts.merge(w, 1, Integer::sum);
}
System.out.println(counts.get("to")); // 2
System.out.println(counts.get("not")); // 1
System.out.println(counts.getOrDefault("maybe", 0)); // 0
System.out.println(counts.containsKey("or")); // true
}
}getOrDefault(key, fallback)returns the value, or the fallback if the key is missing.merge(key, 1, Integer::sum)puts1if the key is new. If the key already exists, it adds1to the old value.
Without merge, you would write the same count like this:
counts.put(w, counts.getOrDefault(w, 0) + 1);Both lines give the same result. merge is shorter.
Keys Need equals and hashCode
A HashMap uses a key's hashCode to find where the key is stored. It then uses equals to confirm the match. String and Integer already define both methods correctly. If you use your own class as a key, you must override both, as an earlier chapter showed. Otherwise two keys with the same fields will be treated as different keys.
Exercise
What does this code print? Map<String, Integer> m = new HashMap<>(); m.put("a", 1); m.put("a", 5); m.merge("a", 2, Integer::sum); System.out.println(m.get("a") + " " + m.size());
Show answer
It prints "7 1". The second put replaces 1 with 5, then merge adds 2 to get 7. There is only one key, "a", so the size is 1.
Exercise
You have a Map<String, Integer> called stock. Write one line that prints the stock for "plums", printing 0 if "plums" is not in the map.
Show answer
System.out.println(stock.getOrDefault("plums", 0));