Sub topic 3
Key-Value Lookup with Map and HashMap
Map and HashMap
A Map is a collection that stores pairs. Each pair has a key (the thing you look up by) and a value (the thing you get back). Keys are unique, but values can repeat. HashMap is the most common Map. It finds keys quickly, using the equals and hashCode methods you met earlier.
The program below counts words:
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
}
}put(k, v)stores a value under a key. If the key already has a value, the new value replaces it.get(k)returns the value, ornullif the key is missing.getOrDefault(k, d)returnsdwhen the key is missing.merge(k, 1, Integer::sum)stores 1 the first time it sees a key. After that, it adds 1 to the old value.
Walking Through a Map and Keeping Order
You can loop over a map in three ways:
entrySet()gives you each key and value together.keySet()gives you only the keys.values()gives you only the values.
A HashMap does not promise any order. LinkedHashMap keeps keys in the order you added them. TreeMap keeps keys sorted.
import java.util.Map;
import java.util.TreeMap;
public class MapIterationDemo {
public static void main(String[] args) {
Map<String, Integer> stock = new TreeMap<>();
stock.put("pears", 4);
stock.put("apples", 10);
stock.put("oranges", 7);
for (Map.Entry<String, Integer> e : stock.entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
// apples = 10
// oranges = 7
// pears = 4
System.out.println(stock.keySet()); // [apples, oranges, pears]
System.out.println(stock.values()); // [10, 7, 4]
}
}Unmodifiable Collections
List.of, Set.of, and Map.of (Java 9 and later) create unmodifiable collections. You cannot change them after you create them.
Choosing the Right Collection
| Need | Pick |
|---|---|
| Ordered items, duplicates allowed | ArrayList |
| No duplicates, fast membership test | HashSet |
| No duplicates, sorted | TreeSet |
| Look up a value by a key | HashMap |
| Keys in insertion order | LinkedHashMap |
| Keys sorted | TreeMap |
Exercise
You need to store student names with their grades and print them in alphabetical order by name. Which Map should you use, and why?
Show answer
Use a TreeMap<String, Integer>. A TreeMap keeps its keys sorted, so looping over entrySet prints the names in alphabetical order.
Exercise
What does counts.get("cat") return if "cat" was never added to a HashMap, and how can you get 0 instead?
Show answer
It returns null. Call counts.getOrDefault("cat", 0) to get 0 instead.